> In other languages, like C++, this would crash your program, but in Objective-C, invoking a method on nil returns a zero value. This greatly simplifies expressions, as it obviates the need to check for nil before doing anything: // For example, this expression... if (name != nil && [name isEqualToString:@"Steve"]) { ... } // ...can be simplified to: if ([name isEqualToString:@"steve"]) { ... } Wow, that is some bad…
Of course, there is one place where you have to go the other way: -isNil: does not work, you need to use -isNotNil
Unless you use the runtime's (private) nil-hook:
+(void)setNilHandler
{
installed=YES;
_objc_setNilReceiver([self nsNil]);
}
Then you can send messages to nil and they will be sent to your class. Of course, you want to mimic the nil-eating behavior as much as possible, so: static id idresult( id receiver, SEL selector, ... ) { return nil; }
+(BOOL)resolveInstanceMethod:(SEL)selector
{
class_addMethod(self, selector, (IMP)idresult , "@@:@");
return YES;
}