NSString 应用 retain 还是 copy

1。对NSString应用retain,效率无疑是最好的

2。用copy最安全,因为NSString 为 NSMutableString 的基类,如果将NSMutableString 以retain的形式赋值给NSString后,后续修改NSMutableString会导致NSString内容的变化,这通常不是我们希望的,所以用copy最安全。

3。到底用哪个?貌似还是用copy,因为copy并不一定导致一个新对对象创建,而牺牲效率。copy会调用NSCopying中的 -(id)copyWithZone:(NSZone *),我们可以判断下self是NSString还是NSMutableString,如果是NSString,就地[self  retain],[return self]。否则老老实实拷贝对象赋值,这样可以实现效率和安全的结合,实验的结果也是如此。

1     NSString* strOrgin = [NSString stringWithFormat:@"curr time is %@", [NSDate date]];
2 
3     NSLog(@"strOrgin = %p, retainCount = %d", strOrgin, [strOrgin retainCount]);
4 
5     NSString* strCopy = [strOrgin copy];
6 
7     NSLog(@"strCopy = %p, retainCount=%d", strCopy, [strCopy retainCount]);
8 
9     NSLog(@"strOrgin = %p, retainCount = %d", strOrgin, [strOrgin retainCount]);

 

-------------------------------------------out put-------------------------------

1 Test[50250:707] strOrgin = 0x1e52e4d0, retainCount = 1
2 
3 Test[50250:707] strCopy = 0x1e52e4d0, retainCount=2
4 
5 Test[50250:707] strOrgin = 0x1e52e4d0, retainCount = 2

 

 -----------------------------------------------------------------------

文档貌似对此也隐约有所说明。

所有用copy就ok了,其他有可变派生类的对象情况类似,但应用的时候根据具体需求就好了。

参考文档 NSCopying Protocol Reference

Your options for implementing this protocol are as follows:

  • Implement NSCopying using alloc and init... in classes that don’t inherit copyWithZone:.
  • Implement NSCopying by invoking the superclass’s copyWithZone: when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject function, make explicit assignments to pointer instance variables for retained objects.
  • Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.

 

posted on 2012-10-31 18:12  武松  阅读(1063)  评论(2编辑  收藏  举报