How to compare two NSArrays for equal content?

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

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

    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 arr2 after 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, NSSet creation time is far more than NSArray - source.

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

提交回复
热议问题