• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Why is [nil aMessage] a no-op?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

References: 
 >Why is [nil aMessage] a no-op? (From: Adam P Jenkins <email@hidden>)
 >Re: Why is [nil aMessage] a no-op? (From: Bill Bumgarner <email@hidden>)
 >Re: Why is [nil aMessage] a no-op? (From: Adam P Jenkins <email@hidden>)
 >Re: Why is [nil aMessage] a no-op? (From: Bill Bumgarner <email@hidden>)
 >Re: Why is [nil aMessage] a no-op? (From: Adam P Jenkins <email@hidden>)

  • Prev by Date: Re: Why is [nil aMessage] a no-op?
  • Next by Date: Re: @dynamic and Programmatic Access to Setters
  • Previous by thread: Re: Why is [nil aMessage] a no-op?
  • Next by thread: Re: Why is [nil aMessage] a no-op?
  • Index(es):
    • Date
    • Thread