Which is the right one, nil or NULL, to mark "no Objective-C block"? Which is the right one, nil or NULL, to mark "no Objective-C block"? objective-c objective-c

Which is the right one, nil or NULL, to mark "no Objective-C block"?


Blocks are not represented as function pointers. They're represented as blocks, and this is denoted by the ^ symbol in their declaration. Down under the hood, the only resemblance is the call syntax. Otherwise, they are both very, very different.

It is often useful to call methods on them. For instance, if you don't use garbage collection, you need to call the copy method on blocks if you want to keep them for later. With the advent of automatic retain count, this is even the only way to copy a block, since ARC pointer cast rules prevent you from using the Block_copy macro.

NULL is, depending on your compiler, either just 0 or (void*)0. This would work for any kind of pointer. However, because of the language rules of Objective-C, you'll get a warning if you try to send a message to a type that can't cast directly to id (and an error if you use ARC).

Since it can be useful to send messages to blocks, you should use nil for them.


[EDIT] Let's be clear that using either nil or NULL will result in exactly the same binary code. Your choice of the constant should probably be based on whether you consider blocks to be Objective-C objects or not. This was a bigger deal back in the days when you had to write your own retain and release calls, but now ARC does all the memory management work for you.

If you've used blocks before ARC was a thing, you probably think that they're Objective-C objects. If not, then you probably don't think/realize that they are. There are still a few relics of their identity in the language (for instance, you can have a __weak or __unsafe_unretained pointer to a block), but for the most part, the difference is negligible. Pick one and try to stick with it. I like to think of my blocks as Objective-C objects.