2010-11-01 4 views
1

У меня есть массив объектов. На этом объекте находится свойство NSDecimalNumber distanceFromDevice.Заказать массив по возрастанию

Я хочу заказать этот массив по этой недвижимости. Я много часов боролся с сортировкой, у кого-нибудь был совет?

- (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

См http://stackoverflow.com/questions/805547/ how-to-sort-an-nsmutablearray-with-custom-objects-in-it – AlcubierreDrive

ответ

1

Попробуйте это:

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

Спасибо, не понимайте код, но он работает! :) – TheLearner

-1

U можно сортировать NSArray в возрастающем порядке, таким образом ...

NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil 
ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortedArray; 
sortedArray = [myArrray sortedArrayUsingDescriptors:sortDescriptors]; 
NSLog(@"sortedArray%@",sortedArray); 
Смежные вопросы