2014-03-25 42 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

我剛剛有這個想法,並向下滾動 - 這裏是! –