Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is checking if not nil before sending a release message good practice?

Tags:

objective-c

when releasing an instance that could exist or not, I usually write this:

if (object != nil) [object release];

but since sending a message to nil is not a problem, is that conditional necessary?

I suppose the question comes down to this: which uses more overhead, comparing an object to nil, or sending nil a message?

like image 303
Steph Thirion Avatar asked Nov 25 '08 23:11

Steph Thirion


2 Answers

See this page which explains that passing messages to nil (to generalize your example) is perfectly fine.

As to what has more overhead, any performance impact will be negligible to the overall performance of the system (don't get into the habit of premature optimization).

like image 172
shek Avatar answered Sep 18 '22 16:09

shek


When I was coding more C++ than Obj-C, I would always write code to check for nil -- because it was a note to myself that this pointer is allowed to be nil. Now, I let objc_msgSend deal with it, since I've grown more comfortable reading the code with the assumption that any pointer could validly be nil.

On a "safe coding" level, I think that it's more important to always set your pointers to nil after each release (possibly exluding a release in the dealloc method). This way, you ensure that your pointer is never invalid (it is either valid, or nil).

like image 26
Matt Gallagher Avatar answered Sep 22 '22 16:09

Matt Gallagher