arc中的strong相当于mrc的retain,这一点想必大家都知道,那么NSString类型属性到底应该用copy还是stong修饰呢?直接上代码说明。
@interface Person : NSObject
@property(copy) NSString *copyname;
@property(strong) NSString *strongname;
@end
NSString *name = @"Tom";
NSMutableString *mutableName = [[NSMutableString alloc] initWithString:@"Jim"];
Person *p =[[Person alloc] init];
p.copyname = name;
p.strongname = name;
NSLog(@"%p, %p, %p",p.copyname,p.strongname,name);
//打印结果:0x100001068, 0x100001068, 0x100001068,结论:copyname和strongname都是浅拷贝name
p.copyname = mutableName;
p.strongname = mutableName;
NSLog(@"%p, %p, %p",p.copyname,p.strongname,mutableName);
//打印结果:0x6d694a35, 0x100302140, 0x100302140,结论:copyname深拷贝mutableName, strongname浅拷贝mutableName
[mutableName appendString:@" Green"];
NSLog(@"%@, %@, %@",p.copyname,p.strongname,mutableName);
//打印结果:Jim, Jim Green, Jim Green,结论:copyname未随mutableName改变而改变,而strongname则发生了改变
总结: 对于NSString类型属性而言,如果赋值对象是NSSting,则copy和stong都为浅拷贝,如果赋值对象是NSMutableString,则copy是深拷贝,strong是浅拷贝,所以为了防止赋值对象改变导致属性发生改变,我们应该用copy修饰NSString类型属性。