Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to trap messages sent to nil in Objective-C?

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?

like image 949
Justicle Avatar asked May 27 '09 05:05

Justicle


People also ask

What sending a message to nil means and how is it actually useful?

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 ).

What does @() mean in Objective-C?

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.


1 Answers

You could use a ObjC undocumented trick or dtrace (see the comments for the dtrace solution).

pid$1::objc_msgSend:entry
/arg0==0/
{
  ustack();
}
like image 60
diciu Avatar answered Oct 05 '22 05:10

diciu