ObjectForKey null check

Trying to validate data in item (item NSDictionary


I thought this should work, but I end up in the second if and fail: unrecognized selector sent to instance



    NSArray *galleryArr = [item objectForKey:@"photos"];

    if (galleryArr != nil ) {
        if ([galleryArr count] != 0) {
            //do something


Any ideas?


source to share

3 answers

Add check for [gallryArr isKindOfClass:[NSArray class]]




I solved this problem with this simple Objective-C simple category:

NSDictionary + NotNull.h

#import <Foundation/Foundation.h>

/*! This category extends NSDictionary to work around an issue with NSNull object.
@interface NSDictionary (NotNull)

/*! @abstract Returns the value associated with a given key, but only if the value is not NSNull.
    @param aKey The key for which to return the corresponding value.
    @return The value associated with the given key, or nil if no value is associated with the key, or the value is NSNull.
- (id)objectOrNilForKey:(id)aKey;



NSDictionary + NotNull.m

#import "NSDictionary+NotNull.h"

@implementation NSDictionary (NotNull)

- (id)objectOrNilForKey:(id)aKey
    id object = [self objectForKey:aKey];
    if (object == [NSNull null]) {
        return nil;
    return object;



Now you can just call:

NSArray *galleryArr = [item objectOrNilForKey:@"photos"];




Maybe you will get NSNull

? It is a singleton ( [NSNull null]

) object that represents nil. You can check if([gallryArr isKindOfClass:[NSArray class]])




All Articles