问题描述
NSString
的copy
和retain
有什么区别?
- (void)setString:(NSString*)newString
{
string = [newString copy];
}
推荐答案
在一般情况下,保留一个对象会将其保留计数增加一.这将有助于将对象保留在内存中并防止它被吹走.这意味着,如果您只持有它的保留版本,您就可以与传递给您的任何人共享该副本.
In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
无论你如何复制一个对象,都应该创建另一个具有重复值的对象.将此视为克隆.您不会与传递给您的任何人共享克隆.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
尤其是在处理 NSString
时,你可能无法假设给你一个 NSString
的人是真的给你一个 NSString代码>.有人可能会给你一个子类(
NSMutableString
,在这种情况下),这意味着他们可能会在幕后修改值.如果您的应用程序依赖于传入的值,并且有人在您身上更改了它,您可能会遇到麻烦.
When dealing with NSString
s in particular, you may not be able to assume that whoever is giving you an NSString
is truly giving you an NSString
. Someone could be handing you a subclass (NSMutableString
, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.
这篇关于“复制"和“复制"有什么区别?和“保留"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!