Objective C 中的nil,Nil,NULL和NSNull理解

ObjC 裏面的幾個空值符號經常會差點把我搞死,這些基礎的東西一點要弄清楚才行,以提高碼農的基本素質。

nil

  • nil 是 ObjC 對象的字面空值,對應 id 類型的對象,或者使用 @interface 聲明的 ObjC 對象。
  • 例如:
    ?
    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
     
    // __DARWIN_NULL in _types.h
     
    #define __DARWIN_NULL ((void *)0)

Nil

  • Nil 是 ObjC 類類型的書面空值,對應 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

  • NULL 是任意的 C 指針空值。
  • 例如:
    ?
    int *pointerToInt = NULL;
    char *pointerToChar = NULL;
    struct TreeNode *rootNode = NULL;
  • 定義:
    ?
    // in stddef.h
     
    #define NULL ((void*)0)

NSNull

  • NSNull 是一個代表空值的類,是一個 ObjC 對象。實際上它只有一個單例方法:+[NSNull null],一般用於表示集合中值爲空的對象。
  • 例子說明:
    ?
    // 因爲 nil 被用來用爲集合結束的標誌,所以 nil 不能存儲在 Foundation 集合裏。
    NSArray *array = [NSArray arrayWithObjects:@"one", @"two", nil];
     
    // 錯誤的使用
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:nil forKey:@"someKey"];
     
    // 正確的使用
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[NSNull null] forKey:@"someKey"];
  • 定義:
    ?
    /*  NSNull.h
        Copyright (c) 1994-2012, Apple Inc. All rights reserved.
    */
     
    #import <Foundation/NSObject.h>
     
    @interface NSNull : NSObject <NSCopying, NSSecureCoding>
     
    + (NSNull *)null;
     
    @end

NIL 或 NSNil

ObjC 不存在這兩個符號!

小結

雖然 nil, Nil, NULL 的值相同,理解它們之間的書面意義才重要,讓代碼更加明確,增加可讀性。

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章