Currently my below code takes an average 9.27300 every time I run it. This is an iOS application and I can't expect the user to sit there for roughly 10 seconds.
This code takes an array (originalData) of placeObjects
and calculates the distance from the selected location (CLLocation* searched). It does by [searched distanceFromLocation:currentLoc];
Each time the distance is calculated, the distance is stored into keysArray
.
After the first for loop the numbers are then sorted from ascending order.
After that another for loop is made to line up the originalData to follow the same ascending order as the keysArray
.
A side note: I am currently doing this for 500 objects in originalData.
I am calling this method [self sortLocations];
from viewDidLoad.
-(void)sortLocations{
NSLog(@"Start");
[keysArray removeAllObjects];
//originalData is an NSMutableArray
for (int i = 0; i < [originalData count]; i++) {
/* f is global but its:
* f = [[NSNumberFormatter alloc] init];
* [f setNumberStyle:NSNumberFormatterDecimalStyle];
*/
NSNumber* cLat = [f numberFromString:[[originalData objectAtIndex:i] latitude]];
NSNumber* cLng = [f numberFromString:[[originalData objectAtIndex:i] longitude]];
CLLocation* currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]];
//searched is a CLLocation
CLLocationDistance distance = [searched distanceFromLocation:currentLoc];
NSNumber* num = [NSNumber numberWithInt:distance];
[keysArray addObject:num];
}
//lowToHight is this:
// lowToHigh = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
[keysArray sortUsingDescriptors:[NSArray arrayWithObject:lowToHigh]];
[orderedArray removeAllObjects];
for (int i = 0; i < [keysArray count]; i++) {
NSNumber* keyNum = [keysArray objectAtIndex:i];
for (placeObjects* x in originalData){
NSNumber* cLat = [f numberFromString:[x latitude]];
NSNumber* cLng = [f numberFromString:[x longitude]];
CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]];
CLLocationDistance distance = [searched distanceFromLocation:currentLoc];
NSNumber* num = [NSNumber numberWithInt:distance];
if ([num intValue] == [keyNum intValue]) {
[orderedArray addObject:x];
}
}
}
NSLog(@"End");
}