3 ms·
Can you explain this to non Obj-C users? How does it not crash on null pointers?
by kaoD 12y ago
Can you explain this to non Obj-C users? How does it not crash on null pointers?
- pcwalton 12y agoCalling any method ("sending any message" in Objective-C terminology) on a nil receiver does nothing and returns the zero value of the method's result type (a value of the right size with all bits zeroed).
- swolchok 12y agoThe Obj-C function call [foo doSomething] compiles to the equivalent of objc_msgSend(foo, "doSomething"); (for the pedantic, I'm intentionally simplifying and leaving out objc_selfrefs) The first thing objc_msgSend does is check if foo is nil and, if so, returns 0/nil/the all-zero bit pattern/whatever. It can be extremely convenient, but it can also be extremely inconvenient.
- 72deluxe 12y agoVery informative, thanks. I am a C++ developer and recently had to fix a bug in an OSX app using Obj-C, which looks insane syntax to me. This only goes to reaffirm my belief that it's insane. Anyway, I'll carry on reading my ObjC book as obviously the language has uses, although there's a Swift book in the post. Which do I read first though, eh?
- bitwize 12y agoIn Objective-C 'nil' is a special object (internally rwpresented by a null pointer). When the runtime is instructed to invoke any method on nil, the method does nothing and returns nil (rather than crashing). I think this is an artifact of Smalltalk behavior.
- sceutre 12y agoThis is all Objective-C. In Smalltalk sending messages to nil results in a #doesNotUnderstand: runtime exception.