0
votes

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. How to change this NSPredicate

1
Is rel_Players a 1-to-many relationship? - Avi
Yes. 1 team has many players. - Amdx Rux

1 Answers

1
votes

The ANY operator should work:

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).
  • The method does not need to take a mutable array argument. This restricts the use cases to arguments of type NSMutableArray. If you change the parameter type to NSArray * you can use instances of both NSArray and NSMutableArray.
  • The method does not work on the instance context: It does not have a single access to self. You can make a function out of it or – I would prefer that – make it a method of 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