原來不是所有的對象都支援 copy
隻有遵守NSCopying 協定的類才可以發送copy消息
隻有遵守NSMutableCopying 協定的類才可以發送mutableCopy消息
假如發送了一個沒有遵守上訴兩協定而發送 copy或者 mutableCopy,那麼就會發生異常
預設 nsobject沒有遵守這兩個協定
但是 copy和mutableCopy這兩個方法是nsobject定義的
如果想自定義一下copy 那麼就必須遵守NSCopying,并且實作 copyWithZone: 方法
如果想自定義一下mutableCopy 那麼就必須遵守NSMutableCopying,并且實作 mutableCopyWithZone: 方法
看了一下幾個遵守 NSCopying協定的基本上是一些基礎核心類
比如 NSString NSNumber
copy以後,就是傳回一個新的類,你要負責釋放掉,原先被拷貝的retaincount沒有+1 是以,不需要負責釋放
copy和mutableCopy 就是copy傳回後的是不能修改的對象, mutableCopy傳回後是可以修改的對象
下面是實作一個copyWithZone的例子
@interface BankAccount: NSObject <NSCopying>
{
double accountBalance;
long accountNumber;
}
-(void) setAccount: (long) y andBalance: (double) x;
-(double) getAccountBalance;
-(long) getAccountNumber;
-(void) setAccountBalance: (double) x;
-(void) setAccountNumber: (long) y;
-(void) displayAccountInfo;
-(id) copyWithZone: (NSZone *) zone;
@end
-(id) copyWithZone: (NSZone *) zone
{
BankAccount *accountCopy = [[BankAccount allocWithZone: zone] init];
[accountCopy setAccount: accountNumber andBalance: accountBalance];
return accountCopy;
}
深度拷貝和淺拷貝
上面的方法是淺拷貝,意思就是,隻是重新配置設定了BankAccount類的記憶體,并沒有對BankAccount的屬性重新配置設定記憶體
兩個BankAccount的屬性都是指向同一個地方的. 修改了其中一個BankAccount屬性,那麼另外一個BankAccount屬性
也會一起發生變化
深度拷貝
深度拷貝這裡用到一個存檔功能,先把原先的存檔(其實就是序列化對象,然後存到一個檔案,等下可以反序列化出來指派給另外一個對象),然後存到另外的而一個對象中
NSKeyedArchiver 序列化類
NSKeyedUnarchiver 反序列化類
NSArray *myArray1;
NSArray *myArray2;
NSMutableString *tmpStr;
NSMutableString *string1;
NSMutableString *string2;
NSMutableString *string3;
NSData *buffer;
string1 = [NSMutableString stringWithString: @"Red"];
string2 = [NSMutableString stringWithString: @"Green"];
string3 = [NSMutableString stringWithString: @"Blue"];
myArray1 = [NSMutableArray arrayWithObjects: string1, string2, string3, nil];
buffer = [NSKeyedArchiver archivedDataWithRootObject: myArray1];
myArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
tmpStr = [myArray1 objectAtIndex: 0];
[tmpStr setString: @"Yellow"];
NSLog (@"First element of myArray1 = %@", [myArray1 objectAtIndex: 0]);
NSLog (@"First element of myArray2 = %@", [myArray2 objectAtIndex: 0]);
cocoa的屬性也有3種
protected - Access is allowed only by methods of the class and any subclasses. 預設是這個
private - Access is restricted to methods of the class. Access is not available to subclasses.
public - Direct access available to methods of the class, subclasses and code in other module files and classes.
public的變量可以用 -> 操作符通路
參考位址:http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C
http://wenku.baidu.com/view/12d6592fb4daa58da0114af0.html
http://www.techotopia.com/index.php/Objective-C_-_Data_Encapsulation,_Synthesized_Accessors_and_Dot_Notation
關于通路器的詳細文檔
http://cocoacast.com/?q=node/103