Objective-c – Retain counts of IBOutlets

cocoaiphonemacosnibobjective c

While coding always the same questions concerning retain counts of IBOutlets came along: Retain count after unarchiving an object from NIB? When to use @property's for an IBOutlet? Retain or assign while setting? Differences between Mac and iPhone?

So I read The Nib Object Life Cycle from Apple's documentation. Some test apps on Mac and iPhone gave me some strange results. Nevertheless I wrote down a few rules how to handle this issue to stay happy while coding but now wanted to verify with the community and listen to your opinions and experiences:

  1. Always create an IBOutlet for top-level objects. For non-top-level objects if necessary (access needed).
  2. Always provide a property as follows for IBOutlets (and release them where necessary!):
    • Top-level objects on Mac:
      • @property (nonatomic, assign) IBOutlet SomeObject *someObject;
      • @synthesize someObject;
      • [self.someObject release];
    • Non-top-level objects on Mac (no release):
      • @property (nonatomic, assign) IBOutlet NSWindow *window;
      • @synthesize someObject;
    • Top-level objects on iPhone (must retain):
      • @property (nonatomic, retain) IBOutlet SomeObject *someObject;
      • @synthesize someObject;
      • [self.someObject release];
    • Non-top-level objects on iPhone (should retain):
      • @property (nonatomic, retain) IBOutlet UIWindow *window;
      • @synthesize window;
      • [self.window release];

Side notes:

  • On Mac and iPhone outlet connections are made with a setter if available.
  • Top-level objects: "have […] no owning object"
  • Non-top-level objects: "any objects that have a parent or owning object, such as views nested inside view hierarchies."

So the question would be: is this correct and good practice?

I hope you can approve or correct it.

Best Answer

Always have your nibs' File's Owner be a subclass of NSWindowController or NSViewController (on Mac OS X) or UIViewController (on iPhone), and use @property (retain) IBOutlet for all of its outlets, doing appropriate releases in your controller subclass -dealloc method.

This pattern will work fine on both Mac OS X and iPhone OS, because NSWindowController and NSViewController on Mac OS X take implicit ownership of top-level objects for you (and relinquish that in their own -dealloc methods), and iPhone OS doesn't take any implicit ownership of top-level objects for you during nib loading.

Related Topic