Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Settings IBOutlets to nil in dealloc

In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc. If

self.anOutlet = nil

causes a crash as mentioned in the topic, why are they setting the ivar to nil?

In general, why would you set an ivar to nil in the dealloc when you are already calling release?

like image 216
4thSpace Avatar asked Nov 05 '09 17:11

4thSpace


2 Answers

After a release, the pointer is essentially invalid and accessing it again may cause a crash. By setting a variable to nil after release you prevent that crash from happening. There's no harm in accessing a nil pointer.

The example you've linked to simply demonstrates why it's always a good idea to set a variable or ivar to nil after release, even when it looks like the variable/ivar won't be accessed again.

In the example, the anOutlet ivar is actually accessed by the superclass after your dealloc method, so if you don't set it to nil you will get a crash. Scenarios like that are very hard to spot just by looking at the code, so it's a good idea to nil every variable after release, even in dealloc.

like image 96
Darren Avatar answered Nov 07 '22 23:11

Darren


Sending a message on an object that is released causes a crash, sending a message to a nil object is ignored.

like image 1
MarkPowell Avatar answered Nov 08 '22 00:11

MarkPowell