Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
MrDatabase Avatar asked Oct 15 '25 20:10

MrDatabase


2 Answers

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.

like image 120
Wevah Avatar answered Oct 17 '25 12:10

Wevah


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.

like image 25
lemnar Avatar answered Oct 17 '25 12:10

lemnar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!