如何确定是否需要保留或分配财产?

问题描述:

有什么好的规则可以学习何时我应该使用retain,何时使用retain?

Are there any good rules to learn when I should use retain, and when assign?

分配是用于原始值像BOOL,NSInteger或double。对于对象,请使用保留或复制,具体取决于您是要保留对原始对象的引用还是复制它。

Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.

唯一常见的例外是弱引用,您希望保留指向对象的指针,但由于引用周期而无法保留它。一个示例是委托模式,其中对象(例如表视图)保持指向其委托的指针。由于委托对象保留了表视图,因此让表视图保留委托将意味着不会释放任何一个。在这种情况下使用弱引用。在这种情况下,您可以在创建属性时使用assign。

The only common exception is weak references, where you want to keep a pointer to an object but can't retain it because of reference cycles. An example of this is the delegate pattern, where an object (for example a table view) keeps a pointer to its delegate. Since the delegate object retains the table view, having the table view retain the delegate would mean neither one will ever be released. A weak reference is used in this case instead. In this situation you would use assign when you create your property.