2014-03-25 39 views
0

试图在项目 (产品NSDictionaryobjectForKey空检查

我想这应该工作,但我不进入第二,如果和崩溃与检查数据的有效性:
unrecognized selector sent to instance 监守galleryArr(null)

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

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

任何想法?

+0

gallerAr r不是null ..你会得到像'[__dataType count]'无法识别的选择器...总之'galleryArr'被声明为NSArray ..但实际上它不是 – Shubhank

+0

这是来自JSON对象吗?因为你可能会得到'NSNull'的实例,它不等于'nil' –

+0

它来自JSON对象,我试过 if(galleryArr!= [NSNull null]){ 没有工作。 – Boaz

回答

0

添加支票[gallryArr isKindOfClass:[NSArray class]]

0

也许你会得到NSNull?这是一个代表零的单例([NSNull null])对象。你可以检查if([gallryArr isKindOfClass:[NSArray class]])

1

我已经解决了这个问题,有一个简单的这个简单的Objective-C类:

的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; 

@end 

的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; 
} 

@end 

现在你可以拨打电话:

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

我刚刚有这个想法,并向下滚动 - 这里是! –