Object-C属性标签assign,retain,copy区别

You usually need to claim ownership of your instance variables. See the Objective-C memory management rules. With a retain property, your property setter claims ownership of the new value and relinquishes ownership of the old one. With an assign property, the surrounding code has to do this, which is just as mess in terms of responsibilities and separation of concerns. The reason you would use an assign property is in a case where you can’t retain the value (such as non-object types like BOOL or NSRect) or when retaining it would cause unwanted side effects.

Incidentally, in the case of an NSString, the correct kind of property is usually copy. That way it can’t change out from under you if somebody passes in an NSMutableString (which is valid — it is a kind of NSString).

assign: Anything that is not an owning relationship should use assign rather than copy or retain. Paths down the object graph should be owning; paths up the graph (where included) should be non-owning. Otherwise, you will create circular references without having a delegate in the circle.

retain or copy: You should use copy instead of retain for all classes that has a mutable variant. Eg. NSAArray, NSSet, NSDictionary, NSData, NSCharacterSet, NSIndexSet, and NSString.

翻译:

你通常会声明你的实例变量的所有权。看Objective-C内存管理规则:retain属性,属性setter获得新值的所有权和放弃旧值的所有权。assign属性,别的代码做到这一点,这只是理清责任和区分关注点。使用assign属性的一种情况是值不能被保留(如像BOOL或NSRect非对象类型),或保留它会导致不必要的副作用。
顺便说一下,在NSString的情况下,正确的属性通常是copy。这样,如果有人传入一个NSMutableString,属性会未经允许就被改变(这是有效的 – NSMutableString也是一种的NSString)。
assign:凡是不是拥有的关系,应该使用assign,而不是retain或copy。在对象图中的路径,向下是拥有,向上是非拥有。否则,你可能创建出循环引用。
retain或copy:当类拥有mutable子类时,你应该使用copy,而不是retain。例如:NSAArray,NSSet,NSDictionary,NSData的,NSCharacterSet,NSIndexSet,NSString。

参考:http://stackoverflow.com/questions/1380338/objective-c-101-retain-vs-assign-nsstring

4 thoughts on “Object-C属性标签assign,retain,copy区别