Objective-Cにおいてメッセージ送信先のレシーバがnilの場合、Objective-Cランタイムはなにもしない(エラーは発生せずメソッドも呼び出されない)。メソッドが戻り値型を持つ場合、値 0 相当が返却されたかのように振る舞う。
Sending Messages to nil
In Objective-C, it is valid to send a message tonil-- it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message tonilmay also be valid:
- If the method returns an object, then a message sent to
nilreturns0(nil). For example:Person *motherInLaw = [[aPerson spouse] mother];If the
spouseobject here isnil, thenmotheris sent toniland the method returnsnil.The Objective-C Programming Language, Objects, Classes, and Messaging
- If the method returns any pointer type, any integer scalar of size less than or equal to
sizeof(void*), afloat, adouble, along double, or along long, then a message sent tonilreturns0.- If the method returns a
struct, as defined by the OS X ABI Function Call Guide to be returned in registers, then a message sent tonilreturns0.0for every field in thestruct. Otherstructdata types will not be filled with zeros.- If the method returns anything other than the aforementioned value types, the return value of a message sent to
nilis undefined.
ノート:利便性という観点では他プログラミング言語でいうOptional型に似ており、メソッドチェインを簡潔に記述できるようになっている。一方でコンパイラやランタイムによる検査機構がないことで、本質的なバグを潜在化させて問題を先送りするという危険性もある。
関連URL