代码之家  ›  专栏  ›  技术社区  ›  TheLearner

顺序数组升序

  •  1
  • TheLearner  · 技术社区  · 14 年前

    我想按这个属性排序这个数组。我花了好几个小时整理,有人有什么建议吗?

    - (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 回复  |  直到 14 年前
        1
  •  1
  •   ahmet emrah    14 年前

    试试这个:

    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
  •  -1
  •   Pradeep Reddy Kypa    13 年前

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