在Objective-C中按精确整数字典值过滤NSMutableArray异常问题
解决NSPredicate过滤NSMutableArray中字典失败的问题
你遇到的核心问题是类型不匹配:虽然你以为字典里的UserId是字符串格式的整数,但从你提供的JSON数据来看,UserId实际是数字类型(在Objective-C中会被解析为NSNumber),而你用来比较的userId是NSString类型,两者直接用==比较自然无法匹配。
解决方案一:将NSString类型的userId转为NSNumber再比较
把字符串类型的userId转换成NSNumber后,再构建匹配谓词:
NSString* userId = userInfo[@"UserId"]; // 将字符串转成NSNumber类型 NSNumber* userIdNum = @([userId integerValue]); NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(UserId == %@)", userIdNum]; NSArray* filteredArrays = [allData filteredArrayUsingPredicate:predicate];
解决方案二:将字典中的UserId转为字符串再比较
另一种思路是把字典里的NSNumber类型的UserId转换为字符串,再和你的NSString类型的userId做比较:
NSString* userId = userInfo[@"UserId"]; NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(UserId.stringValue == %@)", userId]; NSArray* filteredArrays = [allData filteredArrayUsingPredicate:predicate];
为什么原来的代码失败?
在你的JSON数据里,UserId的值是20、21这种数字(而非"20"、"21"字符串),当JSON解析成Objective-C对象时,这些数字会被转换成NSNumber实例。你用NSString类型的userId去和NSNumber做相等比较,类型不匹配,所以谓词无法找到任何匹配的对象,最终返回空数组。
内容的提问来源于stack exchange,提问作者Mahboob Nur
相关产品推荐
相关产品推荐

