ios 如何比较两个 NSArrays 的相同内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13815097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:29:28  来源:igfitidea点击:

How to compare two NSArrays for equal content?

objective-ciosnsmutablearraynsarrayequals

提问by Ravi

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

我有 2 个 Nsarray,其中 2 个数组的对象相同可能是对象的索引不同,但无论是否存在索引,它都应该打印两者相等

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?

上面的代码打印'Not equal'但它应该打印'Equal'。我怎样才能做到这一点?

回答by rmaddy

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 NSSetobjects.

如果您想在不考虑顺序的情况下进行比较,则需要使用两个NSSet对象。

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

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

回答by OC Rickard

Most of the answers here actually do not work for fairly common cases (see their comments). There is a very good data structure that will solve this problem: NSCountedSet.

这里的大多数答案实际上不适用于相当常见的情况(请参阅他们的评论)。有一个很好的数据结构可以解决这个问题:NSCountedSet

The counted set is unordered, but does care about the number of items present, so you don't end up with @[1, @1, @2] == @[@1, @2, @2].

计数集是无序的,但确实关心存在的项目数,因此您不会以@[1, @1, @2] == @[@1, @2, @2].

NSArray *array1 = @[@1, @1, @2];
NSArray *array2 = @[@1, @2, @2];

NSCountedSet *set1 = [[NSCountedSet alloc] initWithArray:array1];
NSCountedSet *set2 = [[NSCountedSet alloc] initWithArray:array2];

BOOL isEqual = [set1 isEqualToSet:set2];
NSLog(@"isEqual:%d", isEqual);

回答by Srikar Appalaraju

Try this. What I am doing is make a copy of your first array & remove copy elements from the second array. If its empty then its equal, else not equal.

尝试这个。我正在做的是制作第一个数组的副本并从第二个数组中删除副本元素。如果它是空的,那么它是相等的,否则不相等。

This has lesser memory foot print than @rmaddy solution. You create a duplicate of only one array not both arrays...

这比@rmaddy 解决方案具有更少的内存占用。您只创建一个数组的副本,而不是两个数组...

NSMutableArray *copyArray;
if([arr1 count] >= [arr2 count])
{
    copyArray = [NSMutableArray arrayWithArray:arr1];
    [copyArray removeObjectsInArray:arr2];
}
else //c(arr2) > c(arr1)
{
    copyArray = [NSMutableArray arrayWithArray:arr2];
    [copyArray removeObjectsInArray:arr1];
}

if([copyArray count] != 0)
    NSLog('Not Equal');
else
    NSLog('Equal');

UPDATE1:If you want to use arr2after this then its been changed. You need to make a copy of it, then in that case memory-wise its same as what rmaddy solution takes. But still this solution is superior since, NSSetcreation time is far more than NSArray- source.

UPDATE1:如果您想arr2在此之后使用,则已更改。您需要复制它,然后在这种情况下,内存方面与 rmaddy 解决方案所采用的相同。但还是这个方案,因为优越,NSSet创建时间远远超过NSArray-

UPDATE2:Updated to make the answer more comprehensive incase one array is bigger than other.

UPDATE2:更新以使答案更全面,以防一个数组比另一个数组大。

回答by dotAramis

Just like rmaddy said, those NSArrays are not equal. Try this:

就像 rmaddy 说的,那些 NSArrays 是不相等的。尝试这个:

-(BOOL)compareArrayIgnoreIndexes:(NSArray*)arrayOne toArray:(NSArray*)arrayTwo{
    NSSet *setOne=[[NSSet alloc]initWithArray:arrayOne];
    NSSet *setTwo=[[NSSet alloc]initWithArray:arrayTwo];
    return [setOne isEqualToSet:setTwo];
}

回答by Abz Ios

This can be done by using one NSMutableArray.The main point to be remembered is that the larger array should be saved in NSMutableArray. Otherwise it wont work as expected. The code is given below.

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Three", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];//returns the number of difference between two arrays.

回答by Ravi

I found the solution,,we can achieve that by sorting the array elements

我找到了解决方案,我们可以通过对数组元素进行排序来实现

 NSArray *arr1 = [[NSArray alloc]initWithObjects:@"a2223a",@"ab33b",@"a1acdf",@"ac23c45", nil];
    NSArray *arr11 =  [arr1 sortedArrayUsingSelector:@selector(localizedCompare:)];
    NSArray *arr2 = [[NSArray alloc]initWithObjects:@"ab33b",@"ac23c45",@"a1acdf",@"a2223a", nil];
    NSArray *arr22= [arr2 sortedArrayUsingSelector:@selector(localizedCompare:)];
    if([arr11 isEqualToArray:arr22])
    {
        NSLog(@"equal");
    }
    else
    {
        NSLog(@"Not equal");
    }

回答by Mitch Cohen

Another option is to convert the NSArrays to JSON strings, and compare using isEqualToString.

另一种选择是将 NSArrays 转换为 JSON 字符串,并使用 isEqualToString 进行比较。

-(BOOL)isArray:(NSArray *)firstArray equalContentsToArray:(NSArray *)secondArray {
    if (!firstArray) {
        firstArray=@[];
    }

    if (!secondArray) {
        secondArray=@[];
    }

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:firstArray options:0 error:&error];
    NSString *jsonStringOne = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    jsonData = [NSJSONSerialization dataWithJSONObject:secondArray options:0 error:&error];
    NSString *jsonStringTwo = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    BOOL isEqual=NO;

    if ([jsonStringOne isEqualToString:jsonStringTwo]) {
        isEqual=YES;
    }

    return isEqual;
}

I'd be curious as to a performance comparison of all these methods.

我很好奇所有这些方法的性能比较。