How to compare two NSArrays for equal content?

前端 未结 7 1438
旧巷少年郎
旧巷少年郎 2021-02-13 01:58

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

NSArra         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 02:10

    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.

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

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

提交回复
热议问题