Can someone explain to me in detail when I must use each attribute: nonatomic
, copy
, strong
, weak
, and so on, for a declared property, and explain what each does? Some sort of example would be great also. I am using ARC.
This question is related to
objective-c
automatic-ref-counting
declared-property
nonatomic
property means @synthesize
d methods are not going to be generated threadsafe -- but this is much faster than the atomic
property since extra checks are eliminated.
strong
is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong
means that you own the object.
weak
ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB;
is used and a has weak property , than its value will only be valid till objectB remains in memory.
copy
property is very well explained here
strong,weak,retain,copy,assign
are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section
hoping this helps you out a bit...
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
This link has the break down
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property
assign implies __unsafe_unretained ownership.
copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
retain implies __strong ownership.
strong implies __strong ownership.
unsafe_unretained implies __unsafe_unretained ownership.
weak implies __weak ownership.
Source: Stackoverflow.com