iOS中nil、Nil、NULL、NSNull詳解

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:指向一個對象的空指針spa

      Nil:指向一個類的空指針指針

          NULL:指向其餘類型(如:基本類型、C類型)的空指針對象

          NSNull:一般表示集合中的空值blog

相關文章
相關標籤/搜索