MrDatabase
MrDatabase

Reputation: 44455

How does Objective-c handle messages sent to nil objects?

I know it's ok to send the release message to nil objects. What about other messages? The following code prints 0 to the console. I'd like to understand why.

NSArray *a = nil;
int i = [a count];
NSLog(@"%d", i);

Does sending messages to nil objects ever cause errors?

Upvotes: 4

Views: 782

Answers (2)

lemnar
lemnar

Reputation: 4053

objc_msgSend() effectively drops messages to nil. If the method has a non-void return type, it will return something like nil, i.e. 0, NO, or 0.0, although this isn't always guaranteed all return types on all platforms. Thus, the only errors you're likely to encounter are when your object isn't really nil, (e.g. when it's a reference to a deallocated object), or when you don't handle nil as a return type appropriately.

In your example, -count returns an NSUInteger, so the value of i will be 0, since objc_msgSend() will return 0 for a message to nil that should return an NSUInteger.

Upvotes: 4

Wevah
Wevah

Reputation: 28242

Return values from messages to nil objects are guaranteed to return the equivalent of zero for scalar return types, i.e., nil, 0, 0.0, NO, etc.

See here: Sending Messages to nil.

Upvotes: 6

Related Questions