Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the disadvantages of setting every property to strong?

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.

like image 267
Geesh_SO Avatar asked Dec 12 '13 20:12

Geesh_SO


2 Answers

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.

  • If the property being set is primitive, use assign (or do not use ownership qualifier at all)
  • If the property being set is a scalar, immutable object, use strong
  • If the property being set is a scalar, mutable object implementing NSCopying protocol, use copy
  • If the property being set is mutable, and the ownership is transferred to your object, use strong
  • If the property being set is a mutable object implementing NSCopying protocol, but the ownership remains with the caller, use copy
  • If the property being set is a back reference (i.e. a "to parent" property in a "child" object), use 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.

like image 138
Sergey Kalinichenko Avatar answered Sep 20 '22 02:09

Sergey Kalinichenko


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.

like image 39
driis Avatar answered Sep 21 '22 02:09

driis