Re: Why is [nil aMessage] a no-op?
Re: Why is [nil aMessage] a no-op?
- Subject: Re: Why is [nil aMessage] a no-op?
- From: Jens Alfke <email@hidden>
- Date: Thu, 17 Apr 2008 23:13:37 -0700
On 17 Apr '08, at 9:56 PM, Adam P Jenkins wrote:
Can you give an example of where invoking methods on nil objects
would make sense in a non-error-path situation? I'm not trying to
be argumentative here, I'm really curious to know what Objective-C
idioms take advantage of the nil-swallows-messages behavior. Thank
you.
I use this feature constantly, and a lot of other Obj-C code I've seen
over the years does too. It saves an enormous number of 'if'
statements and makes code a lot more concise and readable.
For example, in a typical dealloc method you release all of your
object-pointer instance variables. You can just simply call [_foo
release] instead of having to check it viz. "if(_foo) [_foo release]".
"[aString length]==0" tests for a nil or an empty string. Same goes
for "[aCollection count]".
"newObj = [obj copy]" nicely handles the case where obj==nil;
otherwise you'd have to do
if( obj )
newObj = [obj copy];
else
newObj = nil;
Yes, occasionally some result is unexpectedly nil and I don't discover
the problem immediately because subsequent calls to it are no-ops
instead of failing visibly. But I find this a much lesser problem than
having to deal with the extra code complexity that all the tests for
nil would add.
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden