How to compare two NSArrays for equal content?

前端 未结 7 1422
旧巷少年郎
旧巷少年郎 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:25

    Another option is to convert the NSArrays to JSON strings, and compare using 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.

提交回复
热议问题