Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can you explain this to non Obj-C users? How does it not crash on null pointers?


The 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.


Very 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?


Calling 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).


In 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.


This is all Objective-C. In Smalltalk sending messages to nil results in a #doesNotUnderstand: runtime exception.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: