我什么时候应该在 Objective-C 中使用 nil 和 NULL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1564410/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:21:20  来源:igfitidea点击:

When should I use nil and NULL in Objective-C?

objective-cnullnsnull

提问by Biranchi

This is sample code:

这是示例代码:

NSDictionary *myDictionary = [NSDictionary dictionary];
NSNumber *myNumber = [myDictionary valueForKey: @"MyNumber"];
NSLog(@"myNumber = %@", myNumber); // output myNumber = (null)

if (myNumber == nil)
    NSLog(@"test 1 myNumber == nil");

if (myNumber == NULL)
    NSLog(@"test 2 myNumber == NULL");

if ([myNumber isEqual:[NSNull null]])
    NSLog(@"test 3 myNumber == [NSNull null]");

When should I use nil, NULL and [NSNull null]?

我什么时候应该使用 nil、NULL 和 [NSNull null]?

采纳答案by Alex

You can use nilabout anywhere you can use null. The main difference is that you can send messages to nil, so you can use it in some places where nullcant work.

您可以nil在任何可以使用的地方使用null。主要区别是可以发送消息到nil,所以可以在一些null不能用的地方使用。

In general, just use nil.

一般来说,只需使用nil.

回答by NSResponder

They differ in their types. They're all zero, but NULLis a void *, nilis an id, and Nilis a Class pointer.

它们的类型不同。它们都为零,但是NULL是一个void *nil是一个id,并且Nil是一个类指针。

回答by Shad

nilis an empty value bound/corresponding with an object (the id type in Objective-C). nilgot no reference/address, just an empty value.

nil是与对象(Objective-C 中的 id 类型)绑定/对应的空值。nil没有参考/地址,只有一个空值。

NSString *str = nil;

So nil should be used, if we are dealing with an object.

因此,如果我们正在处理一个对象,则应该使用 nil。

if(str==nil)
    NSLog("str is empty");

Now NULLis used for non-object pointer(like a C pointer) in Objective-C. Like nil, NULLgot no value nor address.

现在NULL用于Objective-C 中的非对象指针(如 C 指针)。像nil一样,NULL没有值也没有地址。

char *myChar = NULL;
struct MyStruct *dStruct = NULL;

So if there is a situation, when I need to check my struct(structure type variable) is empty or not then, I will use:

所以如果有情况,当我需要检查我的结构(结构类型变量)是否为空时,我将使用:

if (dStruct == NULL)
    NSLog("The struct is empty");

Let's have another example, the

再举一个例子,

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

Of key-value observing, the context should be a C pointer or an object reference. Here for the context we can not use nil; we have to use NULL.

键-值观察,上下文应该是C指针或一个对象引用。这里对于上下文我们不能使用nil;我们必须使用NULL

Finally the NSNullclass defines a singleton object used to represent null values in collection objects(NSArray, NSDictionary). The [NSNull null]will returns the singleton instance of NSNull. Basically [NSNull null]is a proper object.

最后,NSNull类定义了一个单例对象,用于表示集合对象(NSArray、NSDictionary)中的空值。在[NSNull空]会返回NSNull的单一实例。基本上[NSNull null]是一个合适的对象。

There is no way to insert a nil object into a collection type object. Let's have an example:

无法将 nil 对象插入到集合类型对象中。让我们举个例子:

NSMutableArray *check = [[NSMutableArray alloc] init];
[check addObject:[NSNull null]];
[check addObject:nil];

On the second line, we will not get any error, because it is perfectly fair to insert a NSNull object into a collection type object. On the third line, we will get "object cannot be nil" error. Because nil is not an object.

在第二行,我们不会得到任何错误,因为将 NSNull 对象插入到集合类型对象中是完全公平的。在第三行,我们会得到“对象不能为空”错误。因为 nil 不是对象。

回答by Chuck

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null]is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray. So if you need to represent a "nil", you can use [NSNull null].

NULL 和 nil 彼此相等,但 nil 是一个对象值,而 NULL 是一个通用指针值((void*)0具体来说)。[NSNull null]是一个在不允许 nil 的情况下代表 nil 的对象。例如,NSArray 中不能有 nil 值。因此,如果您需要表示“nil”,则可以使用[NSNull null].

回答by Colnaghi

I've found the following:

我发现了以下内容:

objc.h

对象文件

#define Nil __DARWIN_NULL   /* id of Nil class */
#define nil __DARWIN_NULL   /* id of Nil instance */

_types.h

_types.h

#define __DARWIN_NULL ((void *)0)

stddef.h

标准定义文件

#undef NULL
#ifdef __cplusplus
#undef __null  // VC++ hack.
#define NULL __null
#else
#define NULL ((void*)0)
#endif

MacTypes.h

MacTypes.h

#ifndef NULL
#define NULL    __DARWIN_NULL
#endif /* ! NULL */
#ifndef nil
    #define nil NULL
#endif /* ! nil */

The way it looks, there's no difference but a conceptual one.

从外观上看,除了概念上没有区别。

回答by Nicolas Manzini

Beware that if([NSNull null])returns true.

当心if([NSNull null])返回true.

回答by Nirav

They both are just typecast zero's. Functionally, there's no difference between them. ie.,

它们都只是类型化的零。在功能上,它们之间没有区别。IE。,

#define NULL ((void*)0)
#define nil ((id)0)

There is a difference, but only to yourself and other humans that read the code, the compiler doesn't care.

有区别,但仅对您自己和阅读代码的其他人而言,编译器并不关心。

One more thing nil is an object value while NULL is a generic pointer value.

另一件事 nil 是对象值,而 NULL 是通用指针值。

回答by Greg Parker

In modern OS X and iOS SDKs:

在现代 OS X 和 iOS SDK 中:

  • niland Niland NULLare identical in Objective-C and in Objective-C++ before C++11.
  • niland Niland std::nullptrare identical in Objective-C++ with C++11.
  • nilNilNULL是在Objective-C相同的,并且在之前C ++ 11目的-C ++。
  • nilNilstd::nullptr是在Objective-C ++与C ++ 11相同。

Stylistically, many people prefer to use nilfor Objective-C objects and NULLor nullptrfor other pointer types. I myself now use nileverywhere.

在风格上,许多人更喜欢使用nilObjective-C 对象和/NULLnullptr其他指针类型。我自己现在nil到处都在使用。

[NSNull null]is a singletonobject use to represent null values in situations where nilis prohibited as a value (typically in a collection object such as an NSArrayor NSDictionary). Number and Value Programming Topics: Using NSNull

[NSNull null]是一个单例对象,用于在nil禁止作为值的情况下表示空值(通常在集合对象中,例如 anNSArrayNSDictionary)。数字和值编程主题:使用 NSNull

回答by Justin Tanner

To expand on a comment from @cobbal:

要扩展来自@cobbal 的评论:

MacTypes.hcontains:

MacTypes.h包含:

#ifndef nil
   #define nil NULL
#endif

回答by Tafkadasoh

As already mentioned, they are the same, but I use either the one or the other depending on the language in which the corresponding framework was written.

如前所述,它们是相同的,但我使用一种或另一种取决于编写相应框架的语言。

For everything related to Objective-C, I use nil. For example:

对于与 Objective-C 相关的所有内容,我使用 nil。例如:

- (BOOL)doSomethingWithObjectsInArray:(NSArray *)anArray {
    if (anArray == nil) return NO;

    // process elements
    ...
}

However, when checking validity of data models from a C-framework (like AddressBook framework and CoreFoundation), I use NULL. For example:

但是,当从 C 框架(如 AddressBook 框架和 CoreFoundation)检查数据模型的有效性时,我使用 NULL。例如:

- (BOOL)showABUnknownPersonVCForABRecordRef:(ABRecordRef)aRecord {
    if (aRecord == NULL) return NO;

    // set-up the ABUnknownPersonViewController and display it on screen
    ..
}

This way, I have subtle clues in my code if I'm dealing with Obj-C or C based code.

这样,如果我正在处理基于 Obj-C 或 C 的代码,我的代码中有微妙的线索。