现在的位置: 首页 > 综合 > 正文

体会NSString的copy属性

2018年08月29日 ⁄ 综合 ⁄ 共 1095字 ⁄ 字号 评论关闭

原文来自:http://bukkake.iteye.com/blog/954259

规范上NSString做属性都是写成copy的,理论上应该是复制了字符串而不是单纯的增加引用计数,其实问题只会出现在把NSMutableString赋值给NSString的时候。

 

Objective-c代码  收藏代码
  1. @interface Demo : NSObject  
  2. {  
  3.     NSString *retainString;  
  4.     NSString *copyString;  
  5. }  
  6.   
  7. @property (nonatomic, retain)NSString *retainString;  
  8. @property (nonatomic, copy)NSString *copyString;  
  9. @end  
  10.   
  11. @implementation Demo  
  12. @synthesize retainString;  
  13. @synthesize copyString;  
  14. -(void)dealloc  
  15. {  
  16.     [retainString release];  
  17.     [copyString release];  
  18.     [super dealloc];  
  19. }  
  20.   
  21. @end  
  22.   
  23. Demo *o = [[Demo alloc] init];  
  24. NSMutableString *s1 = [[NSMutableString alloc] initWithCapacity:100];  
  25. [s1 setString:@"fuckyou"];  
  26. o.retainString = s1;  
  27. o.copyString = s1;  
  28. NSLog(@"retain string is %@", o.retainString);  
  29. NSLog(@"copy string is %@", o.copyString);  
  30. [s1 setString:@"fuckme"];  
  31. NSLog(@"retain string is %@", o.retainString);  
  32. NSLog(@"copy string is %@", o.copyString);  

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

 

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

抱歉!评论已关闭.