[iOS] Automatic Reference Counting and cross reference

Even with Automatic Reference Counting (ARC) feature in iOS 5, cross reference between objects should still be treated with care. A cross reference is where 2 or more objects are referencing each other, making circular reference. In which case, the reference count on the objects won’t go down to zero and they won’t be automatically deallocated. For example, it can happen on a case like this.

@interface A: NSObject {
  A * parent;
  A * child;
}
@end

If an object is keeping a reference of both its child and parent, the parent and child will have cross-reference between each other. The way to resolve it is by having “__weak” reference on the object with higher hierarchical status, i.e. the parent. In ARC, weak reference means keeping pointer to object without increasing its reference count.

@interface A: NSObject {
  __weak A * parent;
  A * child;
}
@end

Or if you use properties, you can set the property attribute to weak.

@property (weak,nonatomic) A * parent;

Another common case is the delegate pattern. It’s better to set delegate as weak reference too. But one thing should be kept in mind: if you try to access a weak-referenced object which has been deallocated, it will result in bad memory access. So when the delegate object goes out of scope, remember to set the delegate reference to nil.

@protocol B<NSObject>
@end

@interface C: NSObject
@property (weak,nonatomic) id<B> delegate; 
@end
Advertisements
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

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