objectForKey null检查
试图检查项目中的数据的有效性(项目是NSDictionary
)
我认为这应该工作,但我进入第二个,如果和崩溃:
unrecognized selector sent to instance
galleryArr
是(null)
NSArray *galleryArr = [item objectForKey:@"photos"]; if (galleryArr != nil ) { if ([galleryArr count] != 0) { //do something } }
有任何想法吗?
添加一个检查[gallryArr isKindOfClass:[NSArray class]]
。
我用一个简单的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"];
也许你会得到NSNull
? 这是一个单独的( [NSNull null]
)对象,代表零。 你可以检查if([gallryArr isKindOfClass:[NSArray class]])
。