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?
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).
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With