Reputation: 2206
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.
Upvotes: 5
Views: 242
Reputation: 726489
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.
Upvotes: 7
Reputation: 7176
Some super basic rules of thumb:
If you want the object to stick around at least until you are finished with it, go with strong
If you can handle the object disappearing without it hurting you too bad (i.e it is the parent that created you that might be nice to know about but not super important) then use weak
if it is not an NSObject (so is an int, bool float or other primitive type) use assign.
Upvotes: 1
Reputation: 164281
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.
Upvotes: 1
Reputation: 1265
A rule of thumb that I use is: if the object is retained somewhere else, use weak. The biggest thing for me is when using interface builder. If you have an IBOutlet
, you can make it weak, because that object is taken care of in interface builder and in the XIB file
Upvotes: -3