Search code examples
releasedeallociboutlet

When to release IBOutlet?


I used Interface Builder to connect GUI elements to IBOutlet in view controller, but not sure when do I need to release them, in viewDidUnload or dealloc? Or both?

Thanks!


Solution

  • Assuming they're properties, you should set them to nil in both viewDidUnload and dealloc, making sure to use the setter. So e.g.

    self.imageView = nil;
    self.segmentControl = nil;
    /* etc */
    

    Setting a retain property to nil has the effect of releasing the object and setting the instance variable to nil (so it's safe to do the same thing again even without gaining a new object in between).

    viewDidUnload is called when your view controller's view has been ejected from memory, which can happen when a memory warning occurs and your view controller isn't currently using its view. If you've retained some subviews for yourself (implicitly, via a 'retain' setter or deliberately) and don't release them, they'll stay in memory. You don't want them to do that because you're required to free as much memory as possible upon receipt of a memory warning and you or other processes could be terminated if not enough memory is freed system wide. So it's both to be kind to your user and to be a good citizen.

    The same advice applies whether you've got retain or assign properties; if they're retained then setting the property to nil will release, if they're just assigned then setting the property to nil will prevent you from keeping a dangling pointer.