copy、mutableCopy
copy:不管是可变的,还是不可变的,结果都是不可变的
mutableCopy:不管是不可变的,还是可变的,结果都是可变的
NSMutableString *str = [NSMutableString stringWithFormat:@"a"];
NSArray *arr1 = @[str,@"b"];
NSArray *arr2 = [arr1 copy];
[str setString:@"c"];
NSLog(@"%@",arr2);
//自定义的类需要实现copy的话,需要遵守协议NSCopying
@interface UserItem : NSObject<NSCopying,NSMutableCopying>
@property(nonatomic,retain)NSMutableString *name;
@end
@implementation UserItem
//系统没事调用alloc,就相当于调用了allocWithZone
//系统每次调用copy的话,就相当于调用了copyWithZone
-(id)copyWithZone:(NSZone *)zone
{
//实质上创建了一个新的item对象,把它的值赋值过来
UserItem *user = [[[self class] alloc] init];
user.name = self.name;
return user;
}
//深拷贝
-(id)mutableCopyWithZone:(NSZone *)zone
{
UserItem *user = [[[self class] alloc] init];
user.name = [self.name mutableCopy];
return user;
}
@end
UserItem *user = [[UserItem alloc] init];
user.name = [NSMutableString stringWithFormat:@"潘松彪"];
// UserItem *user2 = [user copy]; //浅拷贝
// [user.name setString:@"李力卓”];
UserItem *user3 = [user mutableCopy]; //深拷贝
NSLog(@"%@",user3.name);