I've just been bitten by an annoying bug that was made obscure by the "send message to nil is ok" behaviour in Objective-C.
I've seen Sending a message to nil?, and the consensus seems to be 'thats how we roll' in Objective-C.
Now, maybe I don't have enough experience in Objective-C, but it seems like it would be useful to trap this, because I can't think of a good reason why this should be happening most of the time. However, It could just be a coding idiom I'm not used to yet.
So other than checking for nil everywhere like so:
assert( object != nil );
[object message];
Is there a way to make the runtime trap this condition, and warn when object
is nil?
In Objective-C, it is valid to send a message to nil —it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid: If the method returns an object, then a message sent to nil returns 0 ( nil ).
It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.
You could use a ObjC undocumented trick or dtrace (see the comments for the dtrace solution).
pid$1::objc_msgSend:entry
/arg0==0/
{
ustack();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With