您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 中 nil、Nil、NULL、NSNull 的區別詳解

編輯:iOS 相關教學

這四個「空」寫起來只差大小寫或幾個字母,意思卻完全不同。搞錯雖然常常也能編譯通過,但語意一亂,程式碼的可讀性與正確性都會受影響。

nil:Objective-C 物件的空值

nil 代表一個空的 Objective-C 物件,對應型別是 id,或以 @interface 宣告的物件。

NSString *someString = nil;
NSURL *someURL = nil;
id someObject = nil;

if (anotherObject == nil) {
    // do something
}

定義如下,本質上就是 (void *)0:

// objc.h
#ifndef nil
# if __has_feature(cxx_nullptr)
#  define nil nullptr
# else
#  define nil __DARWIN_NULL
# endif
#endif

// _types.h 中的 __DARWIN_NULL
#define __DARWIN_NULL ((void *)0)

Nil:Objective-C 類別的空值

Nil(大寫 N)專門用於 Class 型別,也就是「類別物件本身」為空。

Class someClass = Nil;
Class anotherClass = [NSString class];

定義方式與 nil 幾乎相同,數值也一樣:

// objc.h
#ifndef Nil
# if __has_feature(cxx_nullptr)
#  define Nil nullptr
# else
#  define Nil __DARWIN_NULL
# endif
#endif

NULL:C 指標的空值

NULL 是純 C 世界裡「任意指標」的空值。

int *pointerToInt = NULL;
char *pointerToChar = NULL;
struct TreeNode *rootNode = NULL;

定義:

// stddef.h
#define NULL ((void*)0)

NSNull:集合中的空值佔位物件

NSNull 是一個類別,是一個真正的 Objective-C 物件,只提供一個單例方法 +[NSNull null]。它存在的唯一理由,是解決「Foundation 集合不能放 nil」這個限制。

// nil 被當作集合的結束標記,因此不能放進 Foundation 集合
NSArray *array = [NSArray arrayWithObjects:@"one", @"two", nil];

// 錯誤用法:nil 會被解讀為參數列表結束
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:nil forKey:@"someKey"];

// 正確用法:用 NSNull 佔位
NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
[dict2 setObject:[NSNull null] forKey:@"someKey"];

定義:

/* NSNull.h — Apple Inc. */
#import <Foundation/NSObject.h>

@interface NSNull : NSObject <NSCopying, NSSecureCoding>
+ (NSNull *)null;
@end

為什麼要分清楚?

雖然 nil、Nil、NULL 三者編譯後的值完全相同,寫在程式碼裡的「語意」卻不同:看到 nil 就知道這裡是物件,看到 NULL 就知道這是 C 指標。堅持用對,程式碼意圖自然清楚。

另外有一個值得牢記的 Objective-C 特性:向 nil 發送訊息不會崩潰,而是安全地回傳 0 或 nil。這與 C 指標解引用的行為完全不同,也是 NSNull 存在的重要背景——從 JSON 解析出的 NSNull 若被誤當成真正的物件使用,就會出 unrecognized selector 例外。處理網路資料時,記得先判斷 [value isKindOfClass:[NSNull class]]。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved