I’m a long time C++ programmer, with a good amount of time in C#. I’m working in Objective C now however, and I’m wondering, is there a downside to sending a message to a nil object in Objective C?
For instance, I’m very used to doing this:
MyClass* c = NULL;
// ...
if( c != NULL ) c->MyMethod();
So in Objective C, I find myself doing:
MyClass* c = nil;
// ...
if( c != nil ) [c MyMethod];
So what I’m wondering is, is there any benefit at all to checking for nil? Is Objective C smart enough to not do any extra weird processing if I try to send a message to nil? Or is there some hidden cost that makes it worthwhile to continue checking for nil?
In Objective-C you do not need to check nil, messaging a nil valid is perfectly valid and most of the times will return nil or 0 if the return value is an integer. The return value is undefined if the return value of the message being passed is a float, double or struct though.