[英]Objective-C copy and retain
When should I use copy instead of using retain? 我何时应该使用复制而不是使用保留? I didn't quite get it.
我没理得。
You would use copy
when you want to guarantee the state of the object. 如果要保证对象的状态,可以使用
copy
。
NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"];
NSString *b = [mutString retain];
[mutString appendString:@"Test"];
At this point b was just messed up by the 3rd line there. 在这一点上,b被第3行搞砸了。
NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"];
NSString *b = [mutString copy];
[mutString appendString:@"Test"];
In this case b is the original string, and isn't modified by the 3rd line. 在这种情况下,b是原始字符串,不会被第3行修改。
This applies for all mutable types. 这适用于所有可变类型。
retain : It is done on the created object, and it just increase the reference count. 保留 :在创建的对象上完成,它只会增加引用计数。
copy -- It creates a new object and when new object is created retain count will be 1. Hope this may help you. copy - 它创建一个新对象,当创建新对象时,保留计数将为1.希望这可以帮助您。
Copy is useful when you do not want the value that you receive to get changed without you knowing. 如果您不希望在不知情的情况下更改收到的值,则复制非常有用。 For example if you have a property that is an
NSString
and you rely on that string not changing once it is set then you need to use copy. 例如,如果您有一个属性是
NSString
并且您依赖该字符串一旦设置就不会更改,那么您需要使用copy。 Otherwise someone can pass you an NSMutableString
and change the value which will in turn change the underlying value of your NSString
. 否则,有人可以传递一个
NSMutableString
并更改该值,该值又会更改NSString
的基础值。 The same thing goes with an NSArray
and NSMutableArray
except copy on an array just copies all the pointer references to a new array but will prevent entries from being removed and added. NSArray
和NSMutableArray
除了数组上的副本只是将所有指针引用复制到新数组,但会阻止删除和添加条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.