Are there any good rules to learn when I should use retain, and when assign?
Assign creates a reference from one object to another without increasing the source's retain count. Retain creates a reference from one object to another and increases the retain count of the source object.
retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. - apple says if you write retain it will auto converted/work like strong only. -
Retain increases the retain count of an object by 1 and takes ownership of an object. Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.
Nonatomic means multiple thread access the variable (dynamic type). Nonatomic is thread unsafe. But it is fast in performance. Nonatomic is NOT default behavior; we need to add nonatomic keyword in property attribute.
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.
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.
I would think that when working with objects you would almost always use retain instead of assign and when working with primitive types, structs, etc, you would use assign (since you can't retain non-objects). That's because you want the object with the property deciding when it is done with the object, not something else. Apple's Memory Management Guide states this:
There are times when you don’t want a received object to be disposed of; for example, you may need to cache the object in an instance variable. In this case, only you know when the object is no longer needed, so you need the power to ensure that the object is not disposed of while you are still using it. You do this with a retain message, which stays the effect of a pending autorelease (or preempts a later release or autorelease message). By retaining an object you ensure that it won’t be deallocated until you are done with it.
For discussion around using copy vs retain, see this SO question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With