[英]Filter is not working in ios
我使用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以获得预期的输出
请遵循以下代码。我在这里使用谓词。
NSPredicate *predit=[NSPredicate predicateWithFormat:@"Price like %@",100];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:predit];
在上面的代码中
如果您提供LIKE,则会提供相同的价格数据。
您必须从代码中删除或删除[dict allValues]。
代替[dict allValues],您需要添加resultArray。因为它是array。
你有这样的数组
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的数组中获取所有值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.