我使用NsPredicate通过一个和多个值来过滤NSMutableArray,首先我尝试通过价格过滤,我已经将NSDictionary值保存到NSMutableArray (即) resultArray,这是我的代码帮助我,
for (int i=0; i<=resultArray.count; i++)
{
NSDictionary *dict=resultArray[i];
NSLog(@"Dict %@",dict);
NSPredicate *predit=[NSPredicate predicateWithFormat:@"(Price == %@)", @"100"];
NSArray *resultAr = [[dict allValues] filteredArrayUsingPredicate:predit];
NSLog(@"Output %@",resultAr);
}
Dict {
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
}结果数组为:
Result (
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
}
) 预期输出为
(
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
}
)但是它给出了错误
reason: '[<__NSCFNumber 0x146db5e0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Price. 上面的代码对于过滤是正确的,否则给我一个过滤resultArray以获得预期输出的想法
发布于 2015-07-14 20:31:02
遵循下面的代码。我在这里使用谓词。
NSPredicate *predit=[NSPredicate predicateWithFormat:@"Price like %@",100];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:predit];在上述代码中
如果你给像这样的,它会给出相同的价格数据。
你必须从代码中删除或移除dict allValues。
你需要添加数组,而不是dict数组,它是resultArray.Because。
发布于 2015-07-14 20:51:39
你有这样的数组
NSArray *arr = @[@{
@"Name": @"Black Eyed Peas",
@"Percentage" : @"0",
@"Price" : @"80"
},
@{
@"Name" : @"Black Gram",
@"Percentage" : @"0",
@"Price" : @"56"
},
@{
@"Name" : @"Channa White",
@"Percentage" : @"0",
@"Price" : @"100"
},
@{
@"Name" : @"Double Beans",
@"Percentage" : @"0",
@"Price" : @"95"
},
@{
@"Name" : @"Gram Dall",
@"Percentage" : @"0",
@"Price" : @"100"
},
@{
@"Name" : @"Green Moong Dal",
@"Percentage" : @"0",
@"Price" : @"150"
},
@{
@"Name" : @"Ground Nut",
@"Percentage" : @"0",
@"Price" : @"140"
},
@{
@"Name" : @"Moong Dal",
@"Percentage" : @"0",
@"Price" : @"75"
},
@{
@"Name" : @"Orid Dal",
@"Percentage" : @"0",
@"Price" : @"100"
},
@{
@"Name" : @"Toor Dal",
@"Percentage" : @"0",
@"Price" : @"150"
}];您只需在此数组上使用谓词,如下所示
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Price like %@",@"100"];
NSArray *arr2 = [arr filteredArrayUsingPredicate:predicate];您将从数组中获取价格为100的所有值
https://stackoverflow.com/questions/31406074
复制相似问题