Objective-C 中的 NULL 与 nil

Objective-C 中的 NULL 与 nil

问题描述:

observeValueForKeyPath:ofObject:change:context: 中 - 为什么文档在未指定上下文指针时使用 NULL 而不是 nil?

In observeValueForKeyPath:ofObject:change:context: - why do the docs use NULL instead of nil when not specifying a context pointer?

nil 应该只用来代替 id,我们 Java 和 C++ 程序员会认为作为指向对象的指针.对非对象指针使用 NULL.

nil should only be used in place of an id, what we Java and C++ programmers would think of as a pointer to an object. Use NULL for non-object pointers.

看那个方法的声明:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
    change:(NSDictionary *)change context:(void *)context

Context 是一个 void *(即 C 风格的指针),所以你肯定会使用 NULL(有时声明为 (void *)0) 而不是 nil(属于 id 类型).

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