简体   繁体   English

使用NSPredicate过滤NSArray

[英]Filtering NSArray with NSPredicate

Its my code : 它是我的代码:

-(NSArray *)searchTeamsWithPlayerPharse:(NSMutableArray *)teams phrase:(NSString *)phrase

{

   NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"rel_Players.fullName CONTAINS[c] %@" ,phrase];
   NSArray *searchResult = [teams filteredArrayUsingPredicate:searchPredicate];


    return searchResult ;
}

It is not working. 它不起作用。 In array I have Team objects. 在数组中,我有团队对象。 Team has relationship with players and i want filtr with this relathionship and find only teams with players have pharse in fullName. 团队与玩家有关系,我希望filtr与这种关系,并发现只有具有玩家的团队在fullName中具有pharse。 How to change this NSPredicate 如何更改此NSPredicate

The ANY operator should work: ANY运算符应工作:

NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"ANY rel_Players.fullName CONTAINS[c] %@" ,phrase];

Some additional remarks: 一些补充说明:

  • a rel_ prefix is unusual and unnecessary: the plural form players is enough and the underscore can be omitted because the beginning of a new word is marked by an uppercase character (camel case). rel_前缀是不常见且不必要的:复数形式的播放器就足够了,并且下划线可以省略,因为新单词的开头用大写字母(驼峰式)标记。
  • The method does not need to take a mutable array argument. 该方法不需要采用可变数组参数。 This restricts the use cases to arguments of type NSMutableArray . 这将用例限制为NSMutableArray类型的参数。 If you change the parameter type to NSArray * you can use instances of both NSArray and NSMutableArray . 如果将参数类型更改为NSArray * ,则可以使用NSArrayNSMutableArray实例。
  • The method does not work on the instance context: It does not have a single access to self . 该方法不适用于实例上下文:它没有对self的单一访问权。 You can make a function out of it or – I would prefer that – make it a method of NSArray . 您可以使用它来做一个函数,或者(我希望这样做)将它NSArray的方法。

Taking this together: 一起考虑:

@interface NSArray(TeamPlayerAddition)
-(NSArray *)teamsWithPlayerPharse:(NSString *)phrase
@end

@implementation NSArray(TeamPlayerAddition)
-(NSArray *)teamsWithPlayerPharse:(NSString *)phrase
{
  NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"ANY rel_Players.fullName CONTAINS[c] %@" ,phrase];
  return [self filteredArrayUsingPredicate:searchPredicate];
}
@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM