NSPredicate 不适用于 ios 中的过滤
Posted
技术标签:
【中文标题】NSPredicate 不适用于 ios 中的过滤【英文标题】:NSPredicate is not working for Filtering in ios 【发布时间】:2015-07-20 13:57:33 【问题描述】:我已尝试通过 NSPredicate 进行过滤。它在 NSMutableArray 中不起作用,但我在 Array 中尝试过,它工作正常。
使用数组的工作代码:
filterArray=[NSMutableArray arrayWithObjects:@"Yvan",@"Balu",@"Srinath",@"Aswin",@"Ram", nil];
NSPredicate *bPredicate =[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'r'"];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:bPredicate];
NSLog(@"Output %@",resultAr);
正确产生:
Output (
Srinath,
Ram
)
我尝试使用包含字典数据的 NSMutableArray,但它不起作用。
结果数组的框架是:
for(int i=0;i<[priceArray count];i++)
cellDict=[[NSMutableDictionary alloc]init];
NSString *nameStr=nameArray[i];
[cellDict setObject:nameStr forKey:@"Name"];
[cellDict setObject:@([splPriceArray[i] intValue]) forKey:@"Percentage"];
[cellDict setObject:@([priceArray[i] intValue]) forKey:@"Price"];
[resultArray addObject:cellDict];
结果数组:
(
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 *predit=[NSPredicate predicateWithFormat:@"Price contains[c] '100'"];
NSPredicate *pred=[NSPredicate predicateWithFormat:@"(Price == %@) AND (Percentage == %@)", @"100",@"0"];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:predit];
以上是正确的方法还是有更好的方法来实现它以获得:
expected output:
(
Name = "Channa White";
Percentage = 0;
Price = 100;
,
Name = "Gram Dall";
Percentage = 0;
Price = 100;
,
Name = "Orid Dal";
Percentage = 0;
Price = 100;
)
【问题讨论】:
【参考方案1】:-
应该是
Price
而不是price
,应该是Percentage
而不是percentage
我猜Percentage
是NSNumber
的类型
我测试
NSDictionary * dic1 = @
@"Name" : @"Black Eyed Peas",
@"Percentage":@(0),
@"Price" : @(80),
;
NSDictionary * dic2 = @
@"Name" : @"Black Eyed Peas",
@"Percentage":@(0),
@"Price" : @(100),
;
NSMutableArray * mutableArray = [[NSMutableArray alloc] initWithArray:@[dic1,dic2]];
NSPredicate *pred= [NSPredicate predicateWithFormat:@"(Price == %@) AND (Percentage == %@)", @(100),@(0)];
NSArray *resultAr = [mutableArray filteredArrayUsingPredicate:pred];
NSLog(@"%@",resultAr);
日志
2015-07-20 22:11:44.535 OCTest[2192:79846] (
Name = "Black Eyed Peas";
Percentage = 0;
Price = 100;
)
【讨论】:
对不起,我尝试了不同的方法,但 'p' 仅是 'P',我更新了我的问题框架结果数组,但我该如何实现你的答案 注意,在我的代码中,是@(100),即NSNumber,而不是@"100" 感谢它现在工作,我将 @"100" & @"0" 更改为 @(100) & @(0)以上是关于NSPredicate 不适用于 ios 中的过滤的主要内容,如果未能解决你的问题,请参考以下文章