2010-11-01 8 views
1

J'ai un tableau d'objets. Sur cet objet est une propriété NSDecimalNumber distanceFromDevice.Ordre du tableau ordre croissant

Je veux commander ce tableau par cette propriété. J'ai lutté pendant des heures avec le tri, n'importe qui a eu n'importe quels conseils?

- (void)buildSearchableListUsing:(CLLocation *)newLocation 
{ 
    listContent = [[NSMutableArray alloc] init]; 

    for(NSAirport *regionalAirport in airportsList) 
    { 
     CLLocation *location = [[CLLocation alloc]initWithLatitude:[regionalAirport.latitude doubleValue] longitude:[regionalAirport.longitude doubleValue]]; 

     regionalAirport.distanceFromDevice = [[NSDecimalNumber alloc]initWithDouble:[newLocation distanceFromLocation:location]]; 

     NSLog(@"distanceFromDevice %@", regionalAirport.distanceFromDevice); 

     [listContent addObject:regionalAirport]; 
    } 

    //I want listContent ordered by the property distanceFromDevice 
} 
+0

Voir http://stackoverflow.com/questions/805547/ comment-trier-un-nsmutablearray-avec-custom-objects-in-it – AlcubierreDrive

Répondre

1

Essayez ceci:

listContent = [[NSMutableArray alloc] init]; 
NSMutableArray *sortArray = [NSMutableArray array]; 
    for(NSAirport *regionalAirport in airportsList) 
    { 
     CLLocation *location = [[CLLocation alloc]initWithLatitude:[regionalAirport.latitude doubleValue] longitude:[regionalAirport.longitude doubleValue]]; 

     regionalAirport.distanceFromDevice = [[NSDecimalNumber alloc]initWithDouble:[newLocation distanceFromLocation:location]]; 

     NSLog(@"distanceFromDevice %@", regionalAirport.distanceFromDevice); 

     //[listContent addObject:regionalAirport]; 
     [sortArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:regionalAirport,@"arrayElement",regionalAirport.distanceFromDevice,@"elementSorter",nil]; 

    } 


    [sortArray sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"elementSorter" ascending:NO] autorelease]]]; 
    for(NSDictionary *dictionary in sortArray) 
    { 
     [listContent addObject:[dictionary valueForKey:@"arrayElement"]]; 
    } 
+0

Merci mon pote, ne comprends pas le code mais ça marche! :) – TheLearner

-1

U peut trier un NSArray de manière ascendante de cette façon ...

NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil 
ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortedArray; 
sortedArray = [myArrray sortedArrayUsingDescriptors:sortDescriptors]; 
NSLog(@"sortedArray%@",sortedArray); 
Questions connexes