Charles Randall
Charles Randall

Reputation: 7310

Is there a downside to sending a message to a nil object in objective c?

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?

Upvotes: 2

Views: 208

Answers (3)

hburde
hburde

Reputation: 1441

Messaging nil is no problem as long as the return value is meaning full in that context. Debugging can get complicated in some instance ...

"If the method returns any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0" (Apple - link below) -- https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html (Sending Message to nil).

Upvotes: 2

Elfred
Elfred

Reputation: 3851

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.

Upvotes: 4

Black Frog
Black Frog

Reputation: 11725

Nope. That is the beauty of Objective-C.

Upvotes: 2

Related Questions