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

I don't think objc has the equivalent of a null pointer exception. You can freely send messages to a deallocated object. Since ARC, it is rare, at least in my experience, running into any memory related issues with objc.
 help



You can send messages to `nil`, but the inverse isn't universally true. APIs like

  [text stringByAppendingString:other]; 
will throw an `NSInvalidArgumentException` if `other` is nil.

That is an API choice from Apple that isn't something inherent to objc. This is true of any method. It is up to the person who wrote it to decide how to handle a nil being passed in.

Frankly, all of this is an API and ABI choice from Apple. It was not the case that sending a message to nil always returned nil/NULL/0 before Apple's Intel transition, and the subsequent introduction of their modern Objective-C ABI. From Apple's 2006 Cocoa coding guidelines:

> If the message sent to nil returns anything other than the aforementioned value types (for example, if it returns any struct type, any floating-point type, or any vector type) the return value is undefined

And from the Intel transition guide:

> messages to a nil object always return 0.0 for methods whose return type is float, double, long double, or long long. Methods whose return value is a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, will return 0.0 for every field in the data structure. Other struct data types will not be filled with zeros. This is also true under Rosetta. On PowerPC Macintosh computers, the behavior is undefined.

This wasn't just a theoretical issue, either. You could run the same Objective-C code on a PPC Mac, an Intel Mac, the iPhone Simulator, and an iPhone – you'd get a zero-filled struct on Intel and the Simulator, while you'd get garbage on PPC and on real iPhone hardware.


You can send messages to null, sendings messages to a deallocated pointer is going to be a bad time.

It’s nice not to crash, but unexpected null can still cause bugs in ObjC when the developer isn’t paying attention.

Having done both ObjC with nonnull annotations, and Swift, I agree that it’d be hard to forgo the having first-class support for Optionals




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

Search: