arc中的strong相當(dāng)于mrc的retain脆荷,這一點(diǎn)想必大家都知道,那么NSString類型屬性到底應(yīng)該用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);
//打印結(jié)果:0x100001068, 0x100001068, 0x100001068,結(jié)論:copyname和strongname都是淺拷貝name
p.copyname = mutableName;
p.strongname = mutableName;
NSLog(@"%p, %p, %p",p.copyname,p.strongname,mutableName);
//打印結(jié)果:0x6d694a35, 0x100302140, 0x100302140,結(jié)論:copyname深拷貝mutableName, strongname淺拷貝mutableName
[mutableName appendString:@" Green"];
NSLog(@"%@, %@, %@",p.copyname,p.strongname,mutableName);
//打印結(jié)果:Jim, Jim Green, Jim Green,結(jié)論:copyname未隨mutableName改變而改變炭分,而strongname則發(fā)生了改變
總結(jié): 對(duì)于NSString類型屬性而言桃焕,如果賦值對(duì)象是NSSting,則copy和stong都為淺拷貝捧毛,如果賦值對(duì)象是NSMutableString观堂,則copy是深拷貝,strong是淺拷貝,所以為了防止賦值對(duì)象改變導(dǎo)致屬性發(fā)生改變呀忧,我們應(yīng)該用copy修飾NSString類型屬性。