這四個看起來都像「空」,混用往往會埋下地雷。它們的型別意義與使用場合其實各不相同的,分清楚之後程式碼意圖也會更清楚。
對應 id 或以 @interface 宣告的 Objective-C 物件。
NSString *someString = nil;
NSURL *someURL = nil;
id someObject = nil;
if (anotherObject == nil) { /* do something */ }
定義:
// objc.h #ifndef nil # if __has_feature(cxx_nullptr) # define nil nullptr # else # define nil __DARWIN_NULL # endif #endif // _types.h #define __DARWIN_NULL ((void *)0)
首字母大寫的 Nil 對應 Class 型別。
Class someClass = Nil; Class anotherClass = [NSString class];
定義方式與 nil 幾乎相同,值也一樣:
#ifndef Nil # if __has_feature(cxx_nullptr) # define Nil nullptr # else # define Nil __DARWIN_NULL # endif #endif
int *pointerToInt = NULL; char *pointerToChar = NULL; struct TreeNode *rootNode = NULL;
定義:
// stddef.h #define NULL ((void*)0)
NSNull 是一個實際存在的類別,只有一個單例方法 +[NSNull null]。它存在的理由是:nil 在 Foundation 集合中被當作「清單結束」的標記,因此不能存進陣列或字典。
// nil 被視為清單結束標記 NSArray *array = [NSArray arrayWithObjects:@"one", @"two", nil]; // 錯誤用法:塞 nil 進字典會崩潰 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:nil forKey:@"someKey"]; // 正確用法 NSMutableDictionary *dict2 = [NSMutableDictionary dictionary]; [dict2 setObject:[NSNull null] forKey:@"someKey"];
定義:
/* NSNull.h */ #import <Foundation/NSObject.h> @interface NSNull : NSObject <NSCopying, NSSecureCoding> + (NSNull *)null; @end
nil、Nil、NULL 三者的底層數值其實相同(都是 0),差別在於表達的語意:物件、類別、C 指標。寫對它們不是為了讓編譯器通過,而是為了讓讀程式碼的人一眼看懂你在操作什麼。而 NSNull 完全不是這一回事——它是個真正的物件,專門用來在集合中佔位。