Objective-C 中的 NULL 与 nil
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/557582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NULL vs nil in Objective-C
提问by erikprice
In observeValueForKeyPath:ofObject:change:context:- why do the docs use NULLinstead of nilwhen not specifying a context pointer?
在observeValueForKeyPath:ofObject:change:context:- 为什么文档使用NULL而不是nil在未指定上下文指针时使用?
回答by Paul Tomblin
nilshould only be used in place of an id, what we Java and C++ programmers would think of as a pointer to an object. Use NULLfor non-object pointers.
nil应该只用来代替 an id,我们 Java 和 C++ 程序员会认为它是指向对象的指针。使用NULL非对象指针。
Look at the declaration of that method:
查看该方法的声明:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
Context is a void *(ie a C-style pointer), so you'd definitely use NULL(which is sometimes declared as (void *)0) rather than nil(which is of type id).
Context 是一个void *(即 C 风格的指针),所以你肯定会使用NULL(有时声明为(void *)0)而不是nil(类型为id)。
回答by Marc Charbonneau
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 *).
它们在技术上是相同的 (0),但 nil 通常用于 Objective-C 对象类型,而 NULL 用于 c 样式指针 (void *)。
回答by Andrew
They're technically the same thing and differ only in style:
它们在技术上是一样的,只是风格不同:
- Objective-C style says
nilis what to use for theidtype (and pointers to objects). - C style says that
NULLis what you use forvoid *. - C++ style typically says that you should just use
0.
- Objective-C 风格说的
nil是用于id类型(和指向对象的指针)的内容。 - C 风格说这
NULL就是你用于void *. - C++ 风格通常说你应该只使用
0.
I typically use the variant that matches the language where the type is declared.
我通常使用与声明类型的语言相匹配的变体。
回答by Andrew
NULLis the C equivalentof nil, a pointer to nothing;
NULL是C equivalentof nil,一个指向空的指针;
where nil is zero typed as id,
其中nil is zero typed as id,
NULL is zero typed as void*.
NULL is zero typed as void*.
One important pointyou can't send a message to NULL. So it is preferred to use nil in objective-C at many places.
重要的一点,您不能向 NULL 发送消息。所以在objective-C中很多地方都倾向于使用nil。
回答by dan14941
They almost are the same thing except,
他们几乎是一样的东西,除了,
nilis used in an Objective-C style.
where NULLis for C type pointers and is typdef'ed to (void *).
nil以Objective-C 风格使用。whereNULL用于 C 类型指针并且被类型化定义为(void *).

