开发者

Do I need to release IBOutlets in dealloc?

开发者 https://www.devze.com 2023-02-06 12:50 出处:网络
I have a View Controller as part of a navigation controller stack with two IBOutlets. In viewDidUnload I free them up:

I have a View Controller as part of a navigation controller stack with two IBOutlets. In viewDidUnload I free them up:

- (void)viewDidUnload
{
    self.myView1 = nil;
    self.myView2 = nil;
    [super viewDidUnload];
}

But I still had a leak. So I stuck release messages in 开发者_开发技巧the dealloc for them too:

- (void)dealloc
{
    [myView1 release];
    [myView2 release];

    [super dealloc];
}

This appears to clear the memory leak. However, I was always told that I should only release ivars that I have created using alloc, copy or new. So I'm worried about these two releases being in here. Is this right or wrong? Can someone please explain this to me because I keep getting conflicting opinions... Thanks!


If any of your @property objects are declared retain or copy, you need to release them in dealloc. This includes your outlets.


By using IBOutlet, the variables are exposed to be connected in Interface Builder and allocated when the view controller is initialized. So they have to be released and deallocated, as the view controller is unloaded and deallocated. Since most IBOutlets are retained UI* properties, this is necessary.

Assigning nils to the variables is technically not deallocating. It's simply the last state to have retain count 0, just before actually being deallocated.

Also, please note they are referenced using self. It means, the references from the view controller becomes nil, not the allocations.

So in conclusion, IBOutlet properties must be released in dealloc()

(Though I am quite confident, someone else may provide 100% correct answer for this.)


The basic, safe pattern is

  • declare ivar
  • declare IBOutlet property for ivar
  • release property in dealloc
  • only reference property, never ivar

The xib sets the property, which release whatever might have been there first.

I'm a bit confused why that leak was there though. Setting the property to nil should release the old reference. Perhaps viewDidUnload wasn't even getting called? Are you sure you even need viewDidUnload?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号