I am using MKMapKit to get the nearest locations in a 100km radius. However I would like to know how I can sort the array into giving me the nearest five annotati开发者_如何转开发ons at the top of the array.
My current code is:
CLLocation *currentlocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
annotation.distanceToTarget = [currentlocation distanceFromLocation:usrlocation];
annotation.title = [dict objectForKey:@"name"];
annotation.subtitle = [NSString stringWithFormat:@"%@, %@, %@",[dict objectForKey:@"street"],[dict objectForKey:@"county"], [dict objectForKey:@"postcode"]];
annotation.subtitle = [annotation.subtitle stringByReplacingOccurrencesOfString:@", ," withString:@""];
if (annotation.distanceToTarget/1000 < 168) {
abc++;
NSLog(@"Distances Lower Than 168: %i", abc);
[storesLessThan100KAway addObject:annotation];
NSLog(@"Stores Count: %i", [storesLessThan100KAway count]);
}
for (int i = 0; i <= 5; i++) {
//NSLog(@"Stores Count For Loop: %i", [storesLessThan100KAway count]);
if ([storesLessThan100KAway count] > 5) {
[mapView addAnnotation:[storesLessThan100KAway objectAtIndex:i]];
}
}
Write your own compare method for annotations:
- (NSComparisonResult)compare:(Annotation *)otherAnnotation {
if (self.distanceToTarget > otherAnnotation.distanceToTarget) {
return NSOrderedDescending;
} else if (self.distanceToTarget < otherAnnotation.distanceToTarget) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}
Then you can sort using a selector:
NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingSelector:@selector(compare:)];
If you're using iOS4, you can use blocks to make this even easier:
NSComparator compareAnnotations = ^(Annotation *obj1, Annotation *obj2) {
if (obj1.distanceToTarget > obj2.distanceToTarget) {
return NSOrderedDescending;
} else if (obj1.distanceToTarget < obj2.distanceToTarget) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
};
NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingComparator:compareAnnotations];
精彩评论