2010-08-16 4 views
0

J'ai actuellement un objet appelé station définie comme:Objective-C NSMutableArray: Problème avec le tri des objets?

@interface RFStation : NSObject { 

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

J'ai aussi un NSMutableArray contenant une liste d'objets « Station ». J'ai besoin d'une méthode pour trier ces objets avec l'attribut 'stationState'.

I mis en œuvre cette méthode:

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

} 

et l'appeler à l'aide:

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

(les données sont chargées dans un UITableViewController)

Quelqu'un peut-il s'il vous plaît me dire pourquoi mon NSMutableArray est ne pas être trié?

Répondre

2

-sortedArrayUsingFunction:… ne modifie pas le tableau. Il ne fait que copier le tableau, le trier et renvoyer le nouveau trié.

Pour trier le tableau modifiable sur place, utilisez la méthode -sortUsingFunction:context:.

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

BTW,

  1. La méthode -compare: retourne déjà NSComparisonResult. Votre fonction doit être mis en œuvre comme

    NSComparisonResult compareCallSign(...) { 
        return [firstStation.stationState compare:secondStation.stationState]; 
    } 
    
  2. vous pouvez simplement utiliser un NSSortDescriptor.

    NSSortDescriptor* sd = [NSSortDescriptor sortDescriptorWithKey:@"stationState" 
                    ascending:YES]; 
    [stationList sortUsingDescriptors:[NSArray arrayWithObject:sd]]; 
    [self.tableView reloadData]; 
    
+0

WOW !! Votre deuxième solution était fantastique .. Merci beaucoup. Maintenant seulement s'il y avait un moyen de donner un +3 pour une solution. – unicornherder

0

bien quelque chose d'évident, vous avez nommé votre méthode de tri compareCallSign et que vous avez passé à compareState sortedArrayUsingFunction

Questions connexes