How to compare two NSArrays for equal content?

Ravi picture Ravi · Dec 11, 2012 · Viewed 21.8k times · Source

I have 2 Nsarray where objects of 2 arrays are same may be indexes of the object differs, but it should print both are equal irrespective of there indexes

NSArray *arr1 = [[NSArray alloc]initWithObjects:@"aa", @"bb", @"1", @"cc", nil];
NSArray *arr2 = [[NSArray alloc]initWithObjects:@"bb", @"cc", @"1", @"aa", nil];

if ([arr1 isEqualToArray:arr2])
{
    NSLog(@"Equal");
}
else
{
    NSLog(@"Not equal");
}

the above code is printing 'Not equal' but it should print 'Equal'. How can I do this?

Answer

rmaddy picture rmaddy · Dec 11, 2012

Those two arrays are not equal. Two arrays are equal is they both have the same objects in the same order.

If you want to compare with no regard to order then you need to use two NSSet objects.

NSSet *set1 = [NSSet setWithArray:arr1];
NSSet *set2 = [NSSet setWithArray:arr2];

if ([set1 isEqualToSet:set2]) {
    // equal
}