views:

58

answers:

2

I currently have an object called Station defined as:

@interface RFStation : NSObject {

    NSString *stationID; 
    NSString *callsign; 
    NSString *logo; 
    NSString *frequency;
@end

I also have an NSMutableArray containing a list of 'Station' objects. I need to have a method to sort these objects by the 'stationState' attribute.

I implemented this method:

NSComparisonResult compareCallSign(RFStation *firstStation, RFStation *secondStation, void *context) {
    if ([firstStation.stationState compare:secondStation.stationState]){
        return NSOrderedAscending;
    }else{
        return NSOrderedDescending;
    }

}

and call it using:

[stationList sortedArrayUsingFunction:compareState context:nil];
[self.tableView reloadData] 

(the data is loaded into a UITableViewController)

Can someone please tell me why my NSMutableArray is not getting sorted?

A: 

well something obvious, you've named your sort method compareCallSign and you've passed compareState to sortedArrayUsingFunction

Gary
+2  A: 

-sortedArrayUsingFunction:… does not modify the array. It just copies the array, sort it, and return the new sorted one.

To sort the mutable array in-place, use the -sortUsingFunction:context: method.

[stationList sortUsingFunction:compareState context:nil];
[self.tableView reloadData];

BTW,

  1. The -compare: method already returns a NSComparisonResult. Your function should be implemented as

    NSComparisonResult compareCallSign(...) {
        return [firstStation.stationState compare:secondStation.stationState];
    }
    
  2. you could just use an NSSortDescriptor.

    NSSortDescriptor* sd = [NSSortDescriptor sortDescriptorWithKey:@"stationState" 
                                                         ascending:YES];
    [stationList sortUsingDescriptors:[NSArray arrayWithObject:sd]];
    [self.tableView reloadData];
    
KennyTM
WOW!! Your second solution was fantastic.. Thank-you soo much. Now only if there was a way to give a +3 for a solution.
dpigera