何时使用retain和何时使用copy [英] When to use retain and when to use copy

查看:109
本文介绍了何时使用retain和何时使用copy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用哪个以及何时使用感到困惑。有经验法则吗?在大多数情况下可以使用它们吗?任何特殊规则?

I'm confused about which to use and when. Is there a rule of thumb? Can in most cases either of them be used? Any special rules?

@property (nonatomic, retain) NSDate *theDateFromPicker;
@property (nonatomic, copy) NSDate *theDateFromPicker;

在这种情况下哪个是最佳选择?

In this case which would be the best choice?

谢谢
-Code

Thanks -Code

推荐答案

当你不想要时,你会想要使用副本对象被另一个对象修改的可能性。

You'll want to use copy when you don't want the possibility that the object gets modified by another object.

一个很好的例子是 NSString 。假设你有这个代码:

A good example is NSString. Let's say you have this code:

@property (nonatomic, retain) NSString *aString;

// in some other class

NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@"test"];
theObject.aString = mutableString; // theObject retains the mutable string

[mutableString setString:@"test2"];

这里发生的是你将值test分配给 aString ,但随后它会被外部修改并变为test2,因为你保留了可变字符串。如果您设置了 copy ,则不会发生这种情况,因为您正在制作可变字符串的副本

What happens here is that you assign the value "test" to aString, but then it gets modified externally and it becomes "test2", because you retained the mutable string. If you had set copy, this wouldn't happen, because you are making a copy of the mutable string.

这篇关于何时使用retain和何时使用copy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆