http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C
下面是一个deep copy的例子:
NSString *myString1 = @"Hello"; NSString *myString2; myString2 = [myString1 mutableCopy];
mac喜欢用mutable这个次来表示deep copy,且不支持运算符重载,所以所有的deep copy都要通过函数来实现,那我们自己如何实现deep copy呢?下面是一个例子,注意黑体部分。
@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; }
int main (int argc, const char * argv[]) { @autoreleasepool { BankAccount *account1; BankAccount *account2; account1 = [BankAccount alloc]; account1 = [account1 init]; [account1 setAccountBalance: 1500.53]; [account1 setAccountNumber: 34543212]; [account1 displayAccountInfo]; account2 = [account1 copy]; [account2 displayAccountInfo]; } return 0; }
最后是一个array deep copy的例子:
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]);