我有一个程序,我很想得到帮助以完全理解。
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