Search code examples
objective-cnsnull

What is the difference between [NSNull new] and [NSNull null]?


I usually use [NSNull new] if I want a NSNull object, but today I noticed that NSNull class provided a class method [NSNull null] to create a NSNull object.

I wonder what is the difference between [NSNull new] and [NSNull null]? is it a wrong way to use [NSNull new] to create an NSNull object?


Solution

  • By the documentation, [... new] equals [[... alloc] init] and creates and returns a new instance for any class that inherits from the NSObject.

    [NSNull null] is a singleton instance that always returns the same instance which is the kCFNull. but if you see the documentation of the NSNull, you can see:

    NSNull (itself) is a singleton object used to represent null values in collection objects that don’t allow nil values.

    So because of the nature of the NSNull, all of them are the same by the instance:

    NSNull* null = [NSNull null];
    NSNull* init = [[NSNull alloc] init];
    NSNull* new = [NSNull new];
    NSNull* kcf = kCFNull;
    

    Demo

    Note how all of them are pointing to the exact same location