0

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?

2 Answers 2

2

-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];
    
Sign up to request clarification or add additional context in comments.

1 Comment

WOW!! Your second solution was fantastic.. Thank-you soo much. Now only if there was a way to give a +3 for a solution.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.