//
// ViewController.m
// NULL nil Test Demo
//
// Created by WeiZhen_Liu on 13-7-29.
//
// http://nshipster.com/nil/
//
/**
NSNull is used throughout Foundation and other frameworks to skirt around the limitations of collections like NSArray and NSDictionary not being able to contain nil values. You can think of NSNull as effectively boxing the NULL or nil value so that it can be used in collections:
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
mutableDictionary[@"someKey"] = [NSNull null]; // Sets value of NSNull singleton for `someKey`
NSLog(@"Keys: %@", [mutableDictionary allKeys]); // @[@"someKey"]
C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context).
Objective-C builds on C's representation of nothing by adding nil. nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.
So to recap, here are the four values representing nothing that every Objective-C programmer should know about:
Symbol Value Meaning
NULL (void *)0 literal null value for C pointers
nil (id)0 literal null value for Objective-C objects
Nil (Class)0 literal null value for Objective-C classes
NSNull [NSNull null] singleton object used to represent null
*/
#import "ViewController.h"
@interface ViewController ()
{
NSObject *_object;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (_object == nil) {
NSLog(@"1"); // output
}
if ([_object isKindOfClass:[NSNull class]]) {
NSLog(@"2"); // no output
}
if ([_object isKindOfClass:[NSObject class]]) { // if _object alloc memory, will output
NSLog(@"3"); // no output
}
if (_object == NULL) {
NSLog(@"4"); // output
}
{
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:0];
mutableDictionary[@"someKey"] = [NSNull null]; // Sets value of NSNull singleton for 'someKey'
// mutableDictionary[@"somekey"] = nil; // will crash
NSLog(@"%@", [mutableDictionary allKeys]); // output
for (NSString *keyStr in [mutableDictionary allKeys]) {
id obj = [mutableDictionary valueForKey:keyStr];
NSLog(@"%@", obj); // output <null>
if ([obj isKindOfClass:[NSNull class]]) {
NSLog(@"NSNull null"); // output
}
}
}
{
NSString *str = @"fs";
if ([str isKindOfClass:[NSString class]]) {
NSLog(@"5");
}
}
{
NSString *str = nil;
if (str == NULL) {
NSLog(@"NULL nil");
// nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.
}
}
}
@end