未使用的IBOutlets泄漏

时间:2010-07-20 13:21:58

标签: iphone objective-c interface-builder

所以,我正在加载XIB文件,它包含一组UIBarButtonItems。调用viewDidLoad:时会使用某些项目。

@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

如果我将上面的ViewController推到UINavigationController上,一切似乎都很好,所有IBOutlet都被分配并且表现得像预期的那样。

我从导航堆栈中弹出ViewController的瞬间乐器的泄漏告诉我,我正在泄漏UIBarButtonItem。祸了我!

如果我将dealloc:更改为

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

没有发生泄漏。如果我在doneButton

中使用viewDidLoad:,也会如此
  NSArray *initialToolbarItems = 
    [[NSArray alloc] initWithObjects: addButton, editButton, doneButton, nil];

我的问题:当我不使用它时,为什么IBOutlet泄露了。我不会在任何时候保留它。 NIB加载器应该拥有该对象,对吗?

3 个答案:

答案 0 :(得分:2)

我能想到的只有:

nib loader将IBOutlets视为强引用。除非您明确指出分配,否则默认保留所有出口。所以你仍然需要在dealloc和viewDidUnload中释放它们。

您还可以使用指定的属性将其作为弱引用:

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

一些阅读:http://weblog.bignerdranch.com/?p=95

答案 1 :(得分:0)

如果你的IBOOutlets声明了@property(保留),那么它们将被保留并且必须被释放

答案 2 :(得分:-1)

数组保留它们