体会NSString的copy属性

规范上NSString做属性都是写成copy的,理论上应该是复制了字符串而不是单纯的增加引用计数,其实问题只会出现在把NSMutableString赋值给NSString的时候(也就是说只有当外界把一个NSMutableString的字符串赋值给类中声明为NSString类型的属性时才产生深拷贝,其他都是浅的)

 也就是说类中的属性不管是NSString还是NSMutableString,只要外界给的类型是可变(Mutable)的,则copy属性才深拷贝

Objective-c代码  

  1. @interface Demo : NSObject  
  • {  
  •     NSString *retainString;  
  •     NSString *copyString;  
  • }  
  •   
  • @property (nonatomic, retain)NSString *retainString;  
  • @property (nonatomic, copy)NSString *copyString;  
  • @end  
  •   
  • @implementation Demo  
  • @synthesize retainString;  
  • @synthesize copyString;  
  • -(void)dealloc  
  • {  
  •     [retainString release];  
  •     [copyString release];  
  •     [super dealloc];  
  • }  
  •   
  • @end  
  •   
  • Demo *o = [[Demo alloc] init];  
  • NSMutableString *s1 = [[NSMutableString alloc] initWithCapacity:100

];  

  • [s1 setString:@"fuckyou"

];  

  • o.retainString = s1;  
  • o.copyString = s1;  
  • NSLog(@"retain string is %@"

, o.retainString);  

  • NSLog(@"copy string is %@"

, o.copyString);  

  • [s1 setString:@"fuckme"

];  

  • NSLog(@"retain string is %@"

, o.retainString);  

  • NSLog(@"copy string is %@"

, o.copyString);  

 这样就可以看出,当使用retain方式的时候,NSMutableString的内容变化时,语义上应该不可变的NSString也变化了,而用copy则是始终保持赋值时的内容。

如果对实际类型就是NSString的对象用了copy,那其实就是retain,你可以通过观察引用计数来发现,而且就语义上来说也完全没有问题,同时也避免了不需要的字符串拷贝的消耗.


原文地址:https://www.cnblogs.com/cnsec/p/11515769.html