comparing arrays in objective-c

前端 未结 5 1956
梦谈多话
梦谈多话 2020-12-09 11:24

Ok a pretty simple question.. in c++ it seems to work but in objective-c i seem to struggle with it :S .. If you want to compare two arrays it should be something like thi

5条回答
  •  -上瘾入骨i
    2020-12-09 12:14

    Here's a little one I put together based on the top ranked example. This merely checks that the arrays contains the same values, irrespective of order and if there are any duplicates. I mainly use this to compare keys of two dictionaries (which often return their allKeys arrays in various sort orders) to see if they contain the same objects. Thanks Peter Hosley for providing the example I adapted this from.

    #pragma mark - Arrays
    // Check to see if arrays contain the same elements, not necessarily in the same order
    // This is different from [array isEqualToArray:responseKeys] which demands the same order in both arrays
    // ## Does not compensate for duplicate entries in an array
    + (BOOL)doArraysContainTheSameObjects:(NSArray *)firstArray withArray:(NSArray *)secondArray {
        BOOL arraysContainTheSameObjects = YES;
    
        for (id myObject in firstArray) {
            if (![secondArray containsObject:myObject]) {
                // We have found an object that is not in the other array.
                arraysContainTheSameObjects = NO;
                break;
            }
        }
        return arraysContainTheSameObjects;
    }
    

提交回复
热议问题