我正在使用MKMapKit来获取100公里范围内最近的位置。但是我想知道如何对数组进行排序,以便在数组顶部给出最接近的五个注释。
我目前的代码是:
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]];
}
}
答案 0 :(得分:1)
为注释编写自己的比较方法:
- (NSComparisonResult)compare:(Annotation *)otherAnnotation {
if (self.distanceToTarget > otherAnnotation.distanceToTarget) {
return NSOrderedDescending;
} else if (self.distanceToTarget < otherAnnotation.distanceToTarget) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}
然后你可以使用选择器进行排序:
NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingSelector:@selector(compare:)];
答案 1 :(得分:-1)
如果您使用的是iOS4,则可以使用块来更轻松地实现这一目标:
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];