NSPredicate for exact match

試著忘記壹切 提交于 2019-12-31 03:53:08

问题


 NSArray *arrData = [NSArray arrayWithObjects:
                    @"cloud,country,plant",
                    @"country,cloud,plant",
                    @"country,plant,cloud",
                    @"clouds,country,plant"
                    ,@"country,clouds,plant",
                    nil];

From above NSArray, I want objects which having a word "cloud"

I tried below code

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(self beginswith %@ OR self contains[CD] %@)",@"cloud",@",cloud"];
NSArray *arrResult = [arrData filteredArrayUsingPredicate:predicate];

But it's giving all 5 objects in arrResult. But I need only 3 (0,1,2) objects.


回答1:


Try:

 NSPredicate* predicate = [NSPredicate predicateWithBlock:^(NSString* string, NSDictionary* options){

    NSArray* array = [string componentsSeparatedByString:@","];

    return [array containsObject:@"cloud"];

}];



回答2:


Try below code,

It will work,

 NSPredicate *hsPredicate = [NSPredicate predicateWithBlock:^BOOL(id  _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        NSArray *sepretArray =[((NSString*)evaluatedObject) componentsSeparatedByString:@","];
        NSPredicate *subPredicate = [NSPredicate predicateWithFormat:@"self == %@",@"cloud"];
        return  ([sepretArray filteredArrayUsingPredicate:subPredicate].count > 0);

    }];
    NSArray *arrResult = [arrData filteredArrayUsingPredicate:hsPredicate];



回答3:


This one do the trick.But i don't know whether it is the efficient way of doing this.

 NSArray *arrData = [NSArray arrayWithObjects:
                    @"cloud,country,plant",
                    @"country,cloud,plant",
                    @"country,plant,cloud",
                    @"clouds,country,plant"
                    ,@"country,clouds,plant",
                    nil];

NSMutableArray *resArray = [[NSMutableArray alloc]init];
for(NSString *tempString in arrData)
{
    NSArray *cache = [tempString componentsSeparatedByString:@","];
    if([cache containsObject:@"cloud"])
      {
        [resArray addObject:tempString];
      }
}


来源:https://stackoverflow.com/questions/37919934/nspredicate-for-exact-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!