Difference between Strong and weak in IOS

Strong

Anytime a pointer variable stores the address of an object, that object is a owner and will stay alive. This is known as a Strong reference. So it means that you want to “own” the object. Only when you set the property to nil will the object be  destroyed.

Why we use Strong

  1. Creates ownership between property and assigned value.
  2. This is default for object property in ARC.

    Weak : A variable can optionally not take ownership of an object it points to. A variable that does not take ownership of an object is known as a weak reference.

    So a Weak property means you don’t want to have control over the objects lifecycle. The object only lives on while another objects has a strong reference to it. If there are no strong references to the object then it will be destroyed. The most common scenario for a weak property is for subviews of a view controllers view. Because these subviews are already strongly held by the view controllers view.

    Why we use Weak

    1. Creates non-ownerships between property and assigned value.
    2. Strong is used on parent object and weak is used on child object when parent is released then child object reference is also set to nil
    3. It helps to prevents retain cycles.
    4. Weak is essentially assigned, unretain property.                                                                                                                                                                                                                                                                                                                                                                                                                                        A weak reference is useful for an unusual situation called a retain cycle. A retain cycle occurs when two or more objects have strong references to each other. This is bad news. When two objects own each other, they will never be destroyed by ARC. Even if every other object in the application releases ownership of these objects, these objects (and any objects that they own) will continue to exist by virtue of those two strong references.Thus, a retain cycle is a memory leak that ARC needs your help to fix. You fix it by making one of the references weak.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s