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?
-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,
The -compare:
method already returns a NSComparisonResult. Your function should be implemented as
NSComparisonResult compareCallSign(...) { return [firstStation.stationState compare:secondStation.stationState]; }
you could just use an NSSortDescriptor.
NSSortDescriptor* sd = [NSSortDescriptor sortDescriptorWithKey:@"stationState" ascending:YES]; [stationList sortUsingDescriptors:[NSArray arrayWithObject:sd]]; [self.tableView reloadData];
显而易见,您已将您的排序方法命名为compareCallSign,并且已将compareState传递给sortedArrayUsingFunction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.