Fastest way to check if an array contains the same objects of another array

后端 未结 10 1926
夕颜
夕颜 2020-12-29 04:36

The goal is to compare two arrays as and check if they contain the same objects (as fast as possible - there are lots of objects in the arrays). The arrays cannot be checked

10条回答
  •  一个人的身影
    2020-12-29 05:15

    Use containsObject: method instead of iterating the whole array.

    NSArray *array;
    array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",                                       @"Luciano", @"Silvia", nil];
    if ([array containsObject: @"Nicola"]) // YES
      {
        // Do something
      }
    

    like this

    + (BOOL)arraysContainSameObjects:(NSArray *)array1 andOtherArray:(NSArray *)array2 {
        // quit if array count is different
        if ([array1 count] != [array2 count]) return NO;
    
        BOOL bothArraysContainTheSameObjects = YES;
    
        for (id objectInArray1 in array1) {
    
            if (![array2 containsObject:objectInArray1])
            {
                bothArraysContainTheSameObjects = NO;
                break;
            }
    
        }
    
        return bothArraysContainTheSameObjects;
    }
    

提交回复
热议问题