Monday, May 30, 2005

Messaging Nil

Peter Ammon:

What does sending a message to nil do in Objective-C? What value does it return? You probably know that if the method is declared to return an object, you get back nil, but what if the method is declared to return a char? An int? A long long? A float? A struct? And how does it all work?

3 Comments RSS · Twitter

You'll get whatever the function objc_msgSend() returns in that case. I suppose it will return null values appropriate to each type, but that's only a guess. See http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/index.html

Raphael, read Peter's post. It's not quite that simple, and objc_msgSend() isn't used in all cases.

There are four objc_msgSend... functions. Two of them are just the replica of the other two for calling super.
There is one function for calling objects that return an object, and one for those who return a struct. I believe the latter is used when the return value is anything like an int, char, float, etc.. It is not specified how it is done, however.
http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html
However, I did a little quick test.
Sending a message to a nil object that's supposed to return an object, you just get nil.
When it's supposed to return an int, you get 0.
So I guess they just made it consistent and return the null value of the corresponding type.

Leave a Comment