Supertecnoboff
Supertecnoboff

Reputation: 6606

Sort NSMutableArray with custom objects

I have an iOS app with a NSMutableArray which contains many rows worth of data (split up into 3 segments) - as shown below:

[PFUser object, stringData, floatValue]
       .             .          4.3
       .             .          5.9
       .             .          1.1
       .             .          9.32
       .             .          0.024

The above diagram shows how the array is split up and the data types that are stored in the array. But those data types are not keys or anything. So I can't do something like valueForKey.

An example of what the array looks like:

@[@[userObject, @"hello", @234.1441],
  @[userObject, @"sdfsg", @94.33],
  @[userObject, @"wrfdo", @24.897]
];

So from the example above you can see that I have arrays in arrays.

I would like to sort the array by reading the 3 segment which contains the float values.

How can I do this? I have looked online and read a lot about using NSSortDescriptor but the problem I have is that all the examples always seem to use simple strings or an array with numbers only.

Is there a way to use NSSortDescriptor in an array with custom objects like mine?

Upvotes: 1

Views: 895

Answers (3)

Pipiks
Pipiks

Reputation: 2048

Try this :

For example in your case to sort the array by float value :

NSMutableArray *array = // Init your array;

array = [NSMutableArray arrayWithArray:[array sortedArrayUsingComparator:^(id obj1, id obj2) {
    float value1 = [[obj1 objectAtIndex:2] floatValue];
    float value2 = [[obj2 objectAtIndex:2] floatValue];

    if (value1 < value2) {
        return (NSComparisonResult)NSOrderedDescending;
    } else if (value1 > value2) {
        return (NSComparisonResult)NSOrderedAscending;
    } else {
        return (NSComparisonResult)NSOrderedSame;
    }
}]];

With this method you can sort as you like.

Upvotes: 3

Cristik
Cristik

Reputation: 32779

You can use sortUsingComparator:

[array sortUsingComparator:^(id obj1, id obj2) {
    NSArray *arr1 = obj1;
    NSArray *arr2 = obj2;
    return [arr1[2] compare:arr2[2]];
}];

Or even (thanks to rmaddy's suggestion):

[array sortUsingComparator:^(NSArray *arr1, NSArray *arr2) {
    return [arr1[2] compare:arr2[2]];
}];

If you have a immutable array, you can use sortedArrayUsingComparator:

Upvotes: 4

JMan Mousey
JMan Mousey

Reputation: 371

NSMutableArray has a call sortUsingComparator, which takes a comparison result block as parameter. So Something like this:

[users sortUsingComparator:
     ^NSComparisonResult(id obj1, id obj2)
     {
         PFUser* userA = (PFUser*)obj1;
         PFUser* userB = (PFUser*)obj2;

        return [userA.floatValue compare:userB.floatValue];

     }];

Upvotes: 0

Related Questions