Re: message to nil? (very basic question)
Re: message to nil? (very basic question)
- Subject: Re: message to nil? (very basic question)
- From: Andrew Abernathy <email@hidden>
- Date: Sat, 19 Jan 2002 19:16:39 -0800
On Saturday, January 19, 2002, at 02:24 PM, Manfred Lippert wrote:
>
Is it allowed to send a message to nil or will it crash or give some
>
runtime
>
errors or such things?
This is not always safe!!! It's covered in the documentation at:
file:///Developer/Documentation/Cocoa/ObjectiveC/3CoreObjC/index.html
But to save you the trouble, the exact quote is:
>
A message to nil also is valid, as long as the message returns an
>
object; if it does, a message sent to nil will return nil. If the
>
message sent to nil returns anything other than an object, the return
>
value is undefined.
Specifically, it's dangerous to message nil with methods that return
floats and structs. You can get away with it with ints because they're
the same size as id, but it's probably not a good idea in general.
Having said that, I frequently use it with ints because it's incredibly
convenient for things like counts (numObjects = [array count];)
It's tempting to use it with booleans as well, but if you do, be very
careful that getting back a NO really means what you think it means in
the case that the target is nil - it's easy to get tripped up with that.
The implementation is architecture-specific, so taking advantage of the
undefined-but-observable behavior could get you in trouble if you ever
try to port your code to another platform.
-andrew