【引用】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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值