How do weak and strong references look like in objective-c?

Centurion picture Centurion · Sep 5, 2011 · Viewed 8.4k times · Source

Wikipedia states "In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector". How do those two types of references look like in code? Does a weak reference is a reference made by an autoreleased message?

Answer

Thilo picture Thilo · Sep 5, 2011

The following answer is for the case when there is no garbage collection (such as on iOS). In the case of garbage collection, there is actually a keyword (__weak) to create a weak reference.

A "weak" reference is a reference that you do not retain.

You need to use these weak references to break up cycles. A common case is a child object that needs a reference to its parent object. In this scenario, the parent would retain a reference to the child object, and the child object has a reference to its parent, but does not retain it. This works because the child object only needs to exist as long as the parent object does.

Does a weak reference is a reference made by an autoreleased message?

Not really, that would be a "very weak reference" ;-)

Auto-released stuff goes away when the call stack is unwound (at the end of every event loop for example). If you need anything to be less temporary, you need to retain a reference (or like in the case above be sure that some other part retains it sufficiently).