我无法弄清楚方法的不同之处

时间:2013-03-17 20:50:40

标签: objective-c class

@interface Rectangle: NSObject
-(void) setOrigin : (XYPoint *) pt;
-(XYPoint *) origin;
...
@end

#import "XYPoint.h"
#import "Rectangle.h"
@implementation Rectangle
-(void) setOrigin : (XYPoint *) pt
{
   origin = pt;
}

-(XYPoint *) origin 
{
   return origin;
}
@end

@interface XYPoint: NSObject
@property int x, y;
-(void) setX: (int) xVall andY; (int) yVal;
@end

#import "XYPoint.h"
@implementation XYPoint
@synthesize x, y
-(void) setX: (int) xVal andY: (int) yVal
{
   x = xVal;
   y = yVal;
}
@end

以上是课程的一部分。 这是主要的

int main (int argc, const char* argv[])
{
    XYPoint* myPoint = [[XYPoint alloc]init];
    Rectangle* myRect = [[Rectangle alloc]init];

    [myPoint setX: 200 andY: 100];

    [myRect setOrigin: myPoint];
    NSLog(@"origin of rectangle: (%i, %i)", myRect.origin.x, myRect.origin.y);
    return 0;
}

这正如我预期的那样正常。但是,如果我改变方法

setOrigin: (XYPoint *) pt

在Rectangle类中,到

-(void) setOrigin: (XYPoint *) pt
{
    origin.x = pt.x;
    origin.y = pt.y;
} 

它只为x和y打印0的值。这两种方法有什么区别。对我来说,似乎是一样的。

1 个答案:

答案 0 :(得分:2)

我打赌你在alloc类的初始化中没有initorigin Rectangle个对象......