Weak References in Mac Cocoa Programming

By: Aaron Hillegass Printer Friendly Format    

Sometimes, you will want to have an object pointer that should point to that object as long as it exists, but you do not want that pointer to prevent the garbage collector from deallocating the object. In this case, you can use a weak reference:

__weak NSFont *favoriteFont;

The garbage collector will feel free to deallocate an object, even if favoriteFont is currently pointing to the object. If favoriteFont is pointing to an object when it is deallocated, favoriteFont is automatically set to nil.

There are also collections (e.g., NSMapTable, NSHashTable, and NSPointerArray) that can hold objects weakly. Also, in a garbage-collected application, the notification center has weak references to the observers.

Most Viewed Articles (in Cocoa )

Latest Articles (in Cocoa)

Comment on this tutorial