订单数组升序

时间:2010-11-01 09:18:41

标签: iphone objective-c

我有一个对象数组。在此对象上是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
}

2 个答案:

答案 0 :(得分: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"]];
    }

答案 1 :(得分:-1)

你可以用这种方式以递增的方式对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);