iOS中nil、Nil、NULL、NSNull詳解_IOS

來源:互聯網
上載者:User

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, Nil, NULL 的值相同,理解它們之間的書面意義才重要,讓代碼更加明確,增加可讀性。

以上所述就是本文的全部內容了,希望大家能夠喜歡。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.