objectively C objectively C - 1 year ago 47
Objective-C Question

How do I sort an array of arrays containing two values in Objective C?

My code for the Array of objects:

NSNumber* myNumber = [f numberFromString:num];

NSMutableArray *tempArr = [[NSMutableArray alloc] init];
[tempArr addObject:startTime];
[tempArr addObject:myNumber];
[_timeSheets addObject:tempArr];

To access the value of myNumber, I use the following code: NSNumber *temp2 = [[_timeSheets objectAtIndex:1] objectAtIndex:1];

I am displaying timeSheets, a mutable array, on a tableView. When the user clicks on a button, I want to reorder and display timeSheets using the smallest myNumber value to the biggest myNumber.

How can I sort the array by using just one value contained in an array of arrays?

Answer Source

NSArray and NSMutableArray offer a number of sorting methods. For your purpose, the easy way would probably be to use -sortUsingComparator: like this:

[_timeSheets sortUsingComparator:^(id obj1, id obj2) {
    if ([obj1 objectAtIndex:1] > [obj2 objectAtIndex:1]) {
        return (NSComparisonResult)NSOrderedDescending;
    if ([obj1 objectAtIndex:1] < [obj2 objectAtIndex:1]) {
        return (NSComparisonResult)NSOrderedAscending;
    return (NSComparisonResult)NSOrderedSame;

The block you supply gets two parameters and returns a NSComparisonResult. Each item in your array is itself an array, so the objects you'll get for obj1 and obj2 are your two-element sub-arrays. The comparison block is applied repeatedly to pairs of objects in the _timeSheets to determine their relative positions.

Note: The comparator block above is based on the example in the NSArray documentation. Look there for more information on sorting.