2011年5月18日 星期三

複製物件 - Setter 與 Getter

*****************************************************************

[newCard setName: newName];


- (void) setName: (NSString *) the Name // <= 這樣可能會有不小心被改到的危險

{

name= theName;

}

*****************************************************************

Copy的方式來做


- (void) setName:(NSString *) theName

{

name = [ theName copy];

} // <= 這樣就不怕了


*********************************************************

//再加上一條

- (void) setName: (NSString *) theName

{

[name autorelease]; // <=加上 autorelease 會將舊的值釋放掉

name= [ theName copy];

}

*********************************************************

//使用合成方法


@property (nonatomic, copy) NSString *name; // nonatomic => 不必使用mutex lock property 暫存器 ,lock住的話可以避免再多工環境下不會同時執行相同的程式碼

// atomic(預設) => 有保護

// nonatomic => 無保護 (執行效率較差)


synthesize 方法

============================================

-(void) setName: (NSString *) the Name

{

if(theName!=name){

[name release];

name=[theName copy];

}

}

*********************************************************

// Getter狀況下 ,則會先 retain 然後 autorelease 實體變數



*********************************************************

// 我們想要複製一個 immutable 的物件的實體變數,卻不想複製物件內容

-(AddressCard *) copyWithZone:(NSZone *) zone

{

AddressCard *newCard = [[ AddressCard allocWithZone: zone ] init];

[newCard retainName: name andEmail: email];

return newCard;

}


-(void) retainName: (NSString *) theName andEmail: (NSString *)theEmail

{

name = [ theName retain];// <= 這裡它沒有複製參數,只有保留 retain 實體變數

email = [ theEmail retain];

}

沒有留言: