订单数组升序
问题描述:
我有一个对象数组。在这个对象上是一个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
}
答
试试这个:
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
答
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);
见http://stackoverflow.com/questions/805547/ how-to-sort-an-nsmutablearray -with-custom-objects-in-it – AlcubierreDrive 2010-11-01 09:31:38