2011-08-20 99 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:'。 –

相關問題