Messages sent to null in Objective-C

28th Dec, 2009 | objective-c

Sending messages to a nil object is safe in Objective-C. This is due to the objc runtime that checks the sender exists before code is executed. Good to know - testing for nil before calling messages on objects is not required, resulting in more concise, readable code.

Example

NSButton *button = nil;

[button setEnabled:YES]; // will NOT crash or cause an exception

[button setAlternateTitle:[button title]]; // will also be ok