As a new iOS programmer, I've had a slew of bugs to fix today, a few of them have been related to me using weak properties instead of strong.
I realise that a good programmer wouldn't have this problem and would only set the properties to strong that need to be, but nonetheless, in my newbie eyes, I can't see why I should use weak, it only adds the risk of problems.
In general, you should decide between weak
, strong
, assign
, and copy
by looking at the relationship between the class holding the property and the value of that property, and also the kind of the property being passed.
assign
(or do not use ownership qualifier at all)strong
NSCopying
protocol, use copy
strong
NSCopying
protocol, but the ownership remains with the caller, use copy
weak
.The concept of ownership is very important in reference counted memory models. This is the primary driving factor behind your decision. You need to decide where is the primary owner of an object, and give that owner a strong reference. If an ownership is shared among a group of objects, give them all a strong reference.
The most difficult situation is when objects could own each other, directly or indirectly. In this case you would be better off replacing "ownership" with "knows about", give all objects a common "top" owner who "owns" everybody, and model the "knows about" relationships with weak
references.
weak
and strong
are very important to get right for memory management purposes.
strong
will increase the reference counter for the pointer, and you effectively say that you own the object.
weak
does not increase the reference counter, and the object can potentially disappear at any time. If you have a cyclic dependency, you should use weak
to avoid a memory leak (two objects both having a strong reference to each other is a cyclic dependency and those objects will never be released).
You should always think about your memory management, but a good rule of thumb is that the property should always be strong
, unless you positively know that it is retained elsewhere. Multiple objects can have a strong
reference to the same object with no problems, as long as no cyclic references occur.
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