我正在循环NSArray
的NSDictionaries
,我当时想要使用NSDictionary
中BOOL
类型中的一个值作为if语句..但是我在做这件事时遇到了一些麻烦。
这就是我的for loop
的样子
for(NSDictionary *dict in arrayOfDictionaries)
{
NSNumber *boolCheck = [dict objectForKey:@"ISREADY"]; // isReady is the bool value which is either 0 or 1
if (boolCheck == [NSNumber numberWithBool:YES]) {
//...
}
}
发生的事情是它循环遍历我的数组,但从未满足我的if语句的条件,即使我100%确定数组中有这种类型的值...并且很多就此而言。
任何帮助,将不胜感激。
假设NSNumber包含BOOL,请尝试
if ([boolCheck boolValue]) {
....
}
来自@Jim Tierney在这里回答:JSON to NSDictionary - How to check the boolean type,一个更精细的方法:
- (BOOL)isBooleanKey:(id)key
{
if ([key isKindOfClass:[NSNumber class]]) {
if([key isEqual:[NSNumber numberWithBool:YES]]
|| [key isEqual:[NSNumber numberWithBool:NO]]){
/* is a bool value if
<key>somekey</key>
<true/> or <false/> ie 1 or 0 but not -1, 2, 3 or 1,8
*/
NSNumber *n = key;
if (n.intValue) {
if (n.intValue >= 0 && n.intValue <= 1) return YES;
}
}
}
// key is not a boolean
return NO;
}
就像这样打电话:
if ([self isBooleanKey:[myDict objectForKey:@"some key"]]) {
// is a bool object for key :-)
}
当相同的密钥可以采用不同的类(NSData,NSString等)时,我遇到了问题,因此boolValue可能会生成异常并失败!上面的代码解决了我