objective-csortingfloating-pointnsarraycomparator

Sort multiple NSArray at the same time - iOS


I have an iOS application which downloads some data from a server. The data includes three main segments: Name (string), address (string) and distance (float).

The said data is stored in three simple NSArray. However I would like to sort the data, so that the results are shown in the following format: Lowest distance first -> highest distance.

I am using Apple's sortedArrayUsingComparator method to sort the distance array. However I have one problem... how can I perform the same sort actions on the other two NSArray so that the data is shown correctly?

This is what I have tried so far:

NSArray *nameData = // string data.....
NSArray *addressData = // string data.....
NSArray *distanceData = // float data.....

distanceData = [distanceData sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    if ([obj1 floatValue] > [obj2 floatValue]) {
        return NSOrderedDescending;
    }

    else if ([obj1 floatValue] < [obj2 floatValue]) {
        return NSOrderedAscending;
    }

    return NSOrderedSame;
}];

As you can see, the above code will sort the "distanceData" array and thats great, but if I only sort the distance array, then the other two arrays will not be in the correct order. So how can I sort the other two array?

Thanks for your time, Dan.


Solution

  • Make one class named Person of type NSObject with properties name, address, distance

    Person.h

    @interface Person : NSObject
    
    @property (strong, nonatomic) NSString *name;
    @property (strong, nonatomic) NSString *address;
    @property (assign, nonatomic) float distance;
    
    @end
    

    Person.m

    @implementation Person
    
    @synthesize name;
    @synthesize address;
    @synthesize distance;
    
    @end
    

    In your view controller, take only 1 array with Person class' object instead of 3 arrays.

    arrPersons = //...Person objects;
    

    Here, you'll get all values. For example:

    Person *p = [arrPersons objectAtIndex:0];
    //p.name
    //p.address
    //p.distance
    

    In this way, you have multiple values of Person object. Based on its property named distance, you can perform sorting. So, you'll get updated Person objects. In this objects, all values will have been sorted.

    NSArray *sortedArray;
    sortedArray = [arrPersons sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        float first = [(Person*)a distance];
        float second = [(Person*)b distance];
        return first > second; //Here, you can use > or < as per ASC or DESC
    }];