NSPredicate完全匹配

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

从NSArray上面,我想要一个有“云”字样的对象

我试过下面的代码

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

但它在arrResult中提供了所有5个对象。 但我只需要3(0,1,2)个对象。

尝试:

  NSPredicate* predicate = [NSPredicate predicateWithBlock:^(NSString* string, NSDictionary* options){ NSArray* array = [string componentsSeparatedByString:@","]; return [array containsObject:@"cloud"]; }]; 

试试下面的代码,

它会工作,

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

这个可以解决问题。但我不知道这是否是有效的方法。

  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]; } }