2011-08-20 94 views
0

我正在学习Objective C。在这里我想出了一个我不明白的问题,请给出一个解决方案。从另一个对象设置一个对象的实例变量

XYPoint.h file 

//header file 
@interface XYPoint:NSObject 
{ 
int x; 
int y; 
} 

@property int x,y; 

-(void) setX:(int) d_x setY:(int)d_y; 

// implementation file XYPoint.m 
@synthesize x,y; 
-(void) setX:(int) d_x setY:(int) d_y 
{ 
x=d_x; 
y=d_y; 
} 

//Rectangle.h file 
@class XYPoint; 
@Interface Rectangle:NSObject 
{ 
int width,height; 
XYPoint *origin; 
} 

@property int width,height; 
-(XYPoint *)origin; 
-(void) setOrigin:(XYPoint*)pt; 

//at implementation Rectangle.m file 
@synthesize width,height; 

-(XYPoint *)origin 
{ 
return origin; 
} 

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


//in main 
#import "Rectangle.h" 
#import "XYPoint.h" 

int main(int argc,char *argv[]) 
{ 
Rectangle *rect=[[Rectangle alloc] init]; 
XYPoint *my_pt=[[XYPoint alloc] init]; 

[my_pt setX:50 setY:50]; 
rect.origin=my_pt; // how is this possible 
return 0; 
} 

在目标c中,我们可以使用点运算符访问实例变量,如果我们声明为属性。但是这里的起源在Rectangle类中声明为实例变量。在主类中,我们使用点访问原始变量。我不知道它是如何工作的。和rect.origin = my_pt行调用setOrigin方法,该行如何调用setOrgin方法。请解释我

回答

2

您对Objective-C属性系统有些误解。

a=obj.property; 

严格相当于呼叫

a=[obj property]; 

obj.property = A;

严格相当于呼叫

[OBJ的setProperty:A];

您应该将@property NSObject*foo声明看作一对方法foosetFoo:的声明以及保留/释放语义的说明。然后执行foosetFoo:。没有比这更多的了。

+0

你说ob.property = a严格等于[obj setProperty:a];所以当我们声明属性并为实例varialbe合成时,我们需要显式地定义setProperty方法。 – Srini

+0

'@synthesize property;'如果你自己没有实现它们(或其中之一),你将为你生成两个方法'property'和'setProperty:'。 –

相关问题