Huang
Huang

Reputation: 1355

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]];

Upvotes: 0

Views: 1380

Answers (1)

akashivskyy
akashivskyy

Reputation: 45180

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

Upvotes: 2

Related Questions