Search code examples
cocoansarraynsset

Troubles using NONE when filtering an NSArray with an NSSet


I'm trying to filter an NSArray by excluding the elements that are in an NSSet. I'm doing something like this:

    NSMutableArray* a = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];
    NSSet* set = [NSSet setWithObjects:@"2", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NONE SELF IN %@", set];
    NSArray* b = [a filteredArrayUsingPredicate:predicate];

However, this code throws an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet

What is that I'm doing wrong?


Solution

  • You should use NOT instead of NONE in the predicate:

    [NSPredicate predicateWithFormat:@"NOT SELF IN %@", set]
    

    It is because the predicate is applied to each object (SELF) in the array, which is NSString. On the contrary, None should be applied on the NSArray of NSSet.

    If you insist on using NONE. You may change a to

    NSMutableArray* a = [NSMutableArray arrayWithObjects:@[@"1"], @[@"2"], @[@"3"], nil];
    

    so that the SELF becomes NSArray.