objective-c copy mutableCopy 拷贝对象

原来不是所有的对象都支持 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 on ly 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 co de 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_-_Da ta_Encapsulation,_Synthesized_Accessors_and_Dot_Notation

关于访问器的详细文档
http://cocoacast.com/?q=node/103


转载:http://donbe.blog.163.com/blog/static/13804802120103272343790/




你可能感兴趣的:(objective-c copy mutableCopy 拷贝对象)