简体   繁体   中英

Order array ascending order

I have an array of objects. On this object is a NSDecimalNumber property distanceFromDevice.

I want to order this array by this property. I have struggled for hours with sorting, anyone got any advice?

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

Try this:

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"]];
    }

U can sort an NSArray in ascending manner in this way...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM