Search code examples
objective-cnsnull

NSDictionary check for null


Is there a quick method for determining if a value is NSNULL in a dictionary without checking for that objects class like

[[dict objectForKey:@"foo"] class] != [NSNull null];


Solution

  • Actually what you have posted is not correct , you are comparing class ( NSNull ) to the singleton instance of this class ( NSNull null ) ,

    the correct would be

    [[dict objectForKey:@"foo"] isKindOfClass:[NSNull class]];
    

    or comparing the instances

    [dict objectForKey:@"foo"] == [NSNull null];
    

    but if you have lots of this calls , you can create a category of NSDictionary and add method there , something like

    - (BOOL)nl_isNSNullAt:(id)key {
        return [[self objectForKey:key] isKindOfClass:[NSNull class]];
    }
    

    or with instances

    - (BOOL)nl_isNSNullAt:(id)key {
        return [self objectForKey:key] == [NSNull null];
    }
    

    then you can directly access

    [dict nl_isNSNullAt:@"foo"]
    

    You can of course choose the name of the method and category ...