简体   繁体   中英

Unused IBOutlets leaking

So, I'm loading by XIB file and it contains a set of UIBarButtonItems . Some of the items are used when the viewDidLoad: is called.

@interface MyViewController : UIViewController  {

  IBOutlet UIBarButtonItem *addButton;
  IBOutlet UIBarButtonItem *editButton;
  IBOutlet UIBarButtonItem *doneButton;
}

// NB: There are no properties retaining anything.

@end

@implementation MyViewController

- (void)viewDidLoad {

  [super viewDidLoad];

  NSArray *initialToolbarItems = 
    [[NSArray alloc] initWithObjects: addButton, editButton, nil];

  self.toolbarItems = initialToolbarItems;
  [initialToolbarItems release];
}

- (void)dealloc {
  [super dealloc];

  // Nothing else to do here since we are not retaining anything.
  // … or are we? <insert dramatic music here>
}

@end

If I push the above the above ViewController onto a UINavigationController everything seems fine, all the IBOutlets are assigned and behave like expected.

The instant i pop the ViewController from the navigation stack Instruments' Leaks tells me that I am leaking a UIBarButtonItem . Woe is me!

If I change dealloc: to

- (void)dealloc {
  [doneButton release];
  [super dealloc];
}

no leaks occur. The same goes if I use doneButton in viewDidLoad:

  NSArray *initialToolbarItems = 
    [[NSArray alloc] initWithObjects: addButton, editButton, doneButton, nil];

My question: Why is my IBOutlet leaking when I don't use it. I don't retain it at any point. The the NIB loader should own the object, right?

Only thing I can think of:

The nib loader treats IBOutlets as strong references. All outlets are retained by default unless you specifically indicate assign. So you still need to release them in dealloc and viewDidUnload.

You can also use a assigned property to make it a weak reference:

@property (nonatomic, assign) IBOutlet UIBarButtonItem *doneButton;

Some reading: http://weblog.bignerdranch.com/?p=95

如果您为IBOOutlet声明了@property并且(保留)声明了它们,它们将被保留并且必须被释放

数组保留它们

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM