码迷,mamicode.com
首页 > 其他好文 > 详细

nil、Nil、NULL与NSNull的区别

时间:2016-04-18 18:36:50      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

1.nil

指向一个对象的指针为空 在objc.h中的定义如下所示:

#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif

在Objective-C中用于id类型的对象

NSString *name = nil;
NSURL    *url  = nil;
id object      = nil;

2.Nil

指向一个类的指针为空 定义如下:

#ifndef Nil
# if __has_feature(cxx_nullptr)
#   define Nil nullptr
# else
#   define Nil __DARWIN_NULL
# endif
#endif

在Objective-C中用于Class类型的对象

Class aClass = Nil;
Clsss bClass = [NSURL class];

3.NULL

指向C类型的指针为空 在stddef.h中定义如下:

#if defined(__need_NULL)
#undef NULL
#ifdef __cplusplus
#  if !defined(__MINGW32__) && !defined(_MSC_VER)
#    define NULL __null
#  else
#    define NULL 0
#  endif
#else
#  define NULL ((void*)0)
#endif

多用于如下例子:

int   *pInt     = NULL;
char *chChar 	= NULL;
struct stStruct = NULL; 

4.NSNull

在Objective-C中是一个类,只是名字中有个Null,NSNull有 + (NSNull *)null; 单例方法,多用于集合(NSArray,NSDictionary)中值为空的对象

NSArray *array = [NSArray arrayWithObjects:
                      [[NSObject alloc] init],
                      [NSNull null],
                      @"aaa",
                      nil,
                      [[NSObject alloc] init],
                      [[NSObject alloc] init], nil];

NSLog(@"%ld", array.count); // 输出 3,NSArray以nil结尾
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                @"Object0", @"Key0",
                                @"Object1", @"Key1",
                                nil,        @"Key-nil"
                                @"Object2", @"Key2",
                                nil];
NSLog(@"%@", dictionary); // 输出2个key-value,NSDictionary也是以nil结尾
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
[mutableDictionary setObject:nil forKey:@"Key-nil"]; // 会引起Crash
[mutableDictionary setObject:[NSNull null] forKey:@"Key-nil"]; // 不会引起Crash

所以在使用时,如下方法是比较安全的

[mutableDictionary setObject:(nil == value ? [NSNull null] : value)
                      forKey:@"Key"];



相信不少开发者,都被NSNull坑过,最常见的是服务器返回的json里面,说好的字典、数组、数字,结果返回的是空值 ,这个时候,NSJSONSerialization 会自动把他们换成 NSNull。当我们再去用dict[@“hello”]的时候,就会出触发exception,导致程序崩溃 解决方法用runtime 给 NSNull写一个分类

如果定义了一个NSArray,为其分配了内存,又想设置其中的内容为空,则可以用[NSNULL null]返回的对对象来初始化NSArray中的内容




nil、Nil、NULL与NSNull的区别

标签:

原文地址:http://www.cnblogs.com/junhuawang/p/5405343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!