尝试检查项目中数据的有效性
(项目为NSDictionary
)
我认为这应该有用,但我确实进入了第二个如果并且崩溃了:
unrecognized selector sent to instance
因为galleryArr
是(null)
NSArray *galleryArr = [item objectForKey:@"photos"];
if (galleryArr != nil ) {
if ([galleryArr count] != 0) {
//do something
}
}
有什么想法吗?
答案 0 :(得分: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"];
答案 1 :(得分:0)
添加[gallryArr isKindOfClass:[NSArray class]]
。
答案 2 :(得分:0)
也许你得到NSNull
?这是一个代表零的单例([NSNull null]
)对象。您可以查看if([gallryArr isKindOfClass:[NSArray class]])
。