Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...