【问题标题】:Order array ascending order排序数组升序
【发布时间】:2010-11-01 09:18:41
【问题描述】:

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

【问题讨论】:

标签: iphone objective-c


【解决方案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"]];
    }

【讨论】:

    【解决方案2】:

    你可以通过这种方式对一个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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多