Objective-c nil, Nil, NULL和NSNul

2018-09-06  本文已影响7人  sun5kong
  1. nil 对象为空
NSObject* obj = nil;
if (nil == obj) {
    NSLog(@"obj is nil");
} else {
    NSLog(@"obj is not nil");
}
  1. Nil 类为空
Class someClass = Nil;
Class anotherClass = [NSString class];
  1. NULL 基本数据对象指针为空
int *pointerToInt = NULL; 
char *pointerToChar = NULL; 
struct TreeNode *rootNode = NULL;
  1. NSNull:
    集合对象无法包含 nil

作为其具体值,如NSArray、NSSet和NSDictionary。相应地,nil 值用一个特定的对象 NSNull 来表示。NSNull 提供了一个单一实例用于表示对象属性中的的nil值。

@interface NSNull : NSObject <NSCopying, NSSecureCoding>
 
+ (NSNull *)null;
 
@end

在NSNull单例类中,提供了唯一的方法null:Returns the singleton instance of NSNull.

NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
mutableDictionary[@"someKey"] = [NSNull null]; // Sets value of NSNull singleton for `someKey`
NSLog(@"Keys: %@", [mutableDictionary allKeys]); // @[@"someKey"]
上一篇下一篇

猜你喜欢

热点阅读