Search code examples
iosobjective-cnsarraynspredicate

NSPredicate to compare identical string arrays?


Is it possible to use nspredicate to compare whether one NSArray is exactly equal to another NSArray of strings? I need this dome via predicates because of its possible I will add this predicate to a compound predicate.

The Array I am comparing against is a property of an NSDictionary.

So the answer was a mixture of both, I did use the predicatewithformat but got creative in the string inside, inspired by @akashivskyy and @avi

  [predicatesArray addObject:[NSPredicate predicateWithFormat:@"ANY dynamic.values == %@", arr]];

Solution

  • Edit: As (partially) suggested by Avi, you may use the equality predicate:

    NSArray *otherArray = @[ @"foo", @"bar" ];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == %@", otherArray];
    
    [predicate evaluateWithObject:@[ @"foo", @"bar" ]]; // YES
    [predicate evaluateWithObject:@[ @"baz", @"qux" ]]; // NO
    

    Alternatively, and if you have any trouble with format string in the future, you may always use a block predicate to perform your own logic:

    NSArray *otherArray = @[ @"foo", @"bar" ];
    
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^(NSArray *evaluatedArray, NSDictionary<NSString *, id> *bindings) {
        return [evaluatedArray isEqualToArray:otherArray];
    }];
    
    // use the predicate