2010-11-01 43 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 2010-11-01 09:31:38

回答

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 2010-11-01 09:38:50

-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);