Reputation: 9273
I have this custom class:
@interface MyModel : NSObject
@property (nonatomic,strong) NSString *id_name;
@property (nonatomic,strong) NSArray *genres;
@end
The genres array is an array of NSNumber
s. I fill another array with the MyModel
object, for example:
MyModel *m = [[MyModel alloc] init];
m.id_name = @"2345";
m.genres = [NSArray arrayWithObjects:[NSNumber numberWithInt:3],[NSNumber numberWithInt:5],nil];
MyModel *m2 = [[MyModel alloc] init];
m2.id_name = @"259";
m2.genres = [NSArray arrayWithObjects:[NSNumber numberWithInt:7],[NSNumber numberWithInt:10],nil];
MyModel *m3 = [[MyModel alloc] init];
m3.id_name = @"25932as";
m3.genres = [NSArray arrayWithObjects:[NSNumber numberWithInt:7],[NSNumber numberWithInt:10],[NSNumber numberWithInt:15],nil];
myArray = [NSArray arrayWithObjects:m,m2,m3,nil];
Now I want to filter myArray
such that the genres are contained within the elements of this array:
NSArray *a = [NSArray arrayWithObjects:[NSNumber numberWithInt:7],[NSNumber numberWithInt:10],nil];
So, myArray
, after filtering, should contain the objects m2
and m3
. Can I do this with NSPredicate
? If so, how? Or is there another way?
Upvotes: 0
Views: 825
Reputation: 18253
Martin R has provided an elegant answer, but if I understand your question correctly, you can also use a simpler predicate:
NSPredicate *allPred = [NSPredicate predicateWithFormat: @"ALL %@ IN genres", a];
NSArray *result = [myArray filteredArrayUsingPredicate: allPred];
This predicate will find MyModel
s that contain all of the genres included in your a
array. In the case of your test data, that will be the two objects with ids 259
and 25932as
.
Upvotes: 1
Reputation: 539715
To find the objects that have at least one genre in the given array a
, use
[NSPredicate predicateWithFormat:@"ANY genres in %@", a];
To find the objects that have all genres in the given array, a SUBQUERY is needed:
[NSPredicate predicateWithFormat:@"SUBQUERY(genres, $g, $g IN %@).@count = %d", a, [a count]];
(The idea is to check if the number of genres that are in the given array is equal to the size of the array.)
Upvotes: 0