2014-05-17 43 views
0

我有一个基本的Rectangle类。我正在试图计算给定原点,宽度和高度的右上角。返回计算对象

我在我的main.m中设置原点,宽度和高度,我可以NSLog它们并获取正确的值。当我尝试在矩形上调用名为upperRight的Rectangle方法时,我得到0,0而不管投入。

下面是我使用的main.m行:Rectangle类的

NSLog(@"The upper right corner is at x=%f and y=%f", myRectangle.upperRight.x, myRectangle.upperRight.y); 

下面是相关的(我认为):

@implementation Rectangle 

{ 
XYPoint *origin; 
XYPoint *originCopy; 
XYPoint *upperRight; 
} 

@synthesize width, height; 

-(XYPoint *) upperRight { 
upperRight.x = origin.x + width; 
upperRight.y = origin.y + height; 
return upperRight; 
} 

即使我尝试设置upperRight。在方法中x = 200,我仍然获得0,0主返回。

我明显缺少一些基本的理解。

编辑:

下面是在主设定值:

Rectangle *myRectangle = [[Rectangle alloc]init]; 
    XYPoint *myPoint = [[XYPoint alloc]init]; 
    XYPoint *testPoint = [[XYPoint alloc]init]; 
    //XYPoint *translateAmount = [[XYPoint alloc]init]; 

    [myRectangle setWidth: 15 andHeight: 10.0]; 
    [myPoint setX: 4 andY: 3]; 

这里的XYPoint.m:

#import "XYPoint.h" 

@implementation XYPoint 

@synthesize x, y; 

-(void) setX:(float)xVal andY:(float)yVal { 
x = xVal; 
y = yVal; 
} 

@end 
+0

你可以显示当你做设置/通话? – Larme

+0

@添加了本地信息 – tangobango

回答

1

假设XYPoint相同CG/NSPoint(一struct有两个float s),那么你为什么要指向他们?

我想你的意思:

implementation Rectangle 
{ 
    XYPoint origin; 
    XYPoint originCopy; 
    XYPoint upperRight; 
} 

// Strange semantics here... a method that modifies upperRight before returning it?!? 
// So why is upperRight an instance variable? Something is rotten in the state of Denmark. 
-(XYPoint) upperRight { 
    upperRight.x = origin.x + width; 
    upperRight.y = origin.y + height; 
    return upperRight; 
} 

这仅仅是猜测,你不透露XYPoint ...

+0

我是初学者。什么是正确的方式来返回上角? – tangobango

+0

@tangobango你需要保持原点和大小(见NS/CGRect)。然后从原点+尺寸计算右上角,因此不需要将右上角作为实例变量。 – trojanfoe

+0

所以我应该主要做这个计算? – tangobango

1

这里就是我最后做适合我原来的方法(不管它是理想的或不,我不知道。)

-(XYPoint *) upperRight { 
XYPoint *result = [[XYPoint alloc]init]; 

result.x = origin.x + width; 
result.y = origin.y + height; 
return result; 
} 
+0

对我来说看起来不错,如果'XYPoint'是适当的Objective-C对象。 – trojanfoe