0

我有一个程序,我很想得到帮助以完全理解。

XYPoint.h:

#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
@property float x, y;
-(void) setX: (float)xVal setY: (float)yVal;
@end

XYPoint.m:

#import "XYPoint.h"
@implementation XYPoint
@synthesize x, y;

-(void) setX:(float)xVal setY:(float)yVal
{
    x = xVal;
    y = yVal;
}
@end

矩形.h:

#import <Foundation/Foundation.h>

@class XYPoint;
@interface Rectangle: NSObject
@property float width, height, tx, ty;

-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
-(void) translate: (XYPoint *) point;
@end

矩形.m:

#import "Rectangle.h"
#import "XYPoint.h"

@implementation Rectangle
{
    XYPoint *origin;
}
@synthesize width, height, tx, ty;
-(void) setWidth: (float) w andHeight: (float) h
{
    width = w;
    height = h;
}

-(void) translate:(XYPoint *)point
{
    tx = origin.x + point.x;
    ty = origin.y + point.y;
}

-(void)setOrigin:(XYPoint *)pt
{
    //if (!origin)
     //  origin = [[XYPoint alloc] init];
    origin.x = pt.x;
    origin.y = pt.y;
}

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

主要的:

#import <Foundation/Foundation.h>
#import "XYPoint.h"
#import "Rectangle.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool
    {

        Rectangle *myRect = [[Rectangle alloc] init];
        XYPoint *vector = [[XYPoint alloc] init];
        XYPoint *origin = [[XYPoint alloc] init];

        [origin setX:10 setY:15];
        [myRect setOrigin:origin];

        [vector setX:30 setY:50];

        [myRect translate:vector];
        NSLog(@"%f , %f", myRect.tx, myRect.ty);

    }
    return 0;
}

在 Rectangle 实现中,有一个if (!origin)用于测试源对象是否已初始化,如果没有,它将分配并初始化它。我不明白为什么当我使用这个测试时我得到了正确的答案,而当我没有得到正确的答案时,我没有得到正确的答案..\有人可以解释一下那里发生了什么吗?tnx

4

1 回答 1

3

您在问题中回答了它:

if (!origin) 来测试origin对象是否被初始化,如果没有,它会分配并初始化它

if (!origin)用于延迟初始化,如果您不初始化它,它将保留nil。Objective-C 允许你在nil没有任何结果的情况下发送消息,所以如果你从不初始化 originorigin.x = pt.x;并且origin.y = pt.y;什么都不做,那么所有依赖于 origin 的数学运算都将使用0.0.

于 2013-02-13T20:20:31.693 回答