Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I want to pass nothing for an Objective-C block, what keyword should I use, NULL or nil? I'm asking this because an Objective-C block is an Objective-C object (as I know), but represented as a function pointer.

NULL and nil both indicate a 0x0 pointer, however they are different semantically. So I'm concerned about this.

like image 510
eonil Avatar asked Apr 23 '11 18:04

eonil


People also ask

Is nil same as null in C?

They're technically the same thing (0), but nil is usually used for an Objective-C object type, while NULL is used for c-style pointers (void *). Also, NULL is differently defined than nil . nil is defined as (id)0 . NULL isn't.

How do you find nil in Objective-C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.


1 Answers

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.

like image 112
zneak Avatar answered Nov 07 '22 05:11

zneak