Which one is correct, null or NULL to mark "no Objective-C block"?

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

NULL and nil both indicate a 0x0 pointer, however they are semantically different. So I worry about that.

+63
syntax objective-c objective-c-blocks
Apr 23 '11 at 18:52
source share
1 answer

Blocks are not represented as pointers to functions. They are represented as blocks, and this is indicated by the ^ symbol in their declaration. Down below the hood, the only similarity is the call syntax. Otherwise, they are both very different.

It is often useful to name methods on them. For example, if you do not use garbage collection, you need to call the copy method on the blocks if you want to save them later. With the advent of automatic account hold, this is even the only way to copy a block, because ARC pointer control rules do not allow the use of the Block_copy macro.

NULL , depending on your compiler, is either just 0 or (void*)0 . This will work for any pointer. However, due to Objective-C language rules, you will receive a warning if you try to send a message to a type that cannot be directly passed to id (and an error if you use ARC).

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




[EDIT] Let it be clear that using either nil or NULL will result in the exact same binary. Your choice of constant should probably be based on whether you think the blocks are Objective-C objects or not. It was a big deal in those days when you had to write your own retain and release calls, but now ARC does all the memory management for you.

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

+83
Apr 23 2018-11-11T00:
source share
— -



All Articles