nil, Nil, NULL, NSNull的区别

nil:指向一个对象的空指针,对Objective-C 的id对象赋空值

  1. nil在指向一个对象的指针为空,定义如下
#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif

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

NSString *str = 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 class1 = Nil;
Class class2 = [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

用于对非对象指针赋空值

   {
            
            struct structStr {
                
            };
            id object = nil;
            Class clas = Nil;
            int *intA = NULL;
            char *charc = NULL;
            struct structStr *cstr = NULL;
        }
  1. NSNull在Objective-C中是一个类 NSNull有+(NSNull *)null单例方法
    多用于集合(NSArray, NSDictionary)中值为空的对象
 {
            
        NSArray *array = [NSArray arrayWithObjects:
            [[NSObject alloc] init],
            [NSNull null],
         
            [[NSObject alloc] init],
            [[NSObject alloc] init], nil];
            NSLog(@"%ld", array.count); // 输出 3,NSArray以nil结尾
            /**
             (lldb) po array
             <__NSArrayI 0x60000195d860>(
             <NSObject: 0x60000157c0f0>,
             <null>,
             <NSObject: 0x60000157c0e0>,
             <NSObject: 0x60000157c100>
             )
             */
        }
  
        {
            
        NSArray *array = [NSArray arrayWithObjects:
            [[NSObject alloc] init],
            [NSNull null],
             nil,
            [[NSObject alloc] init],
            [[NSObject alloc] init], nil];
            NSLog(@"%ld", array.count); // 输出 3,NSArray以nil结尾
            /**
            (lldb) po array
             <__NSArrayI 0x60000017cc20>(
             <NSObject: 0x60000036c120>,
             <null>
             )
            这里重点注意下   NSArray以nil结尾

             */
        }
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                @"Object0", @"Key0",
                                @"Object1", @"Key1",
                                nil,        @"Key-nil"
                                @"Object2", @"Key2",
                                nil];
NSLog(@"%@", dictionary); // 输出2个key-value,NSDictionary也是以nil结尾

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值