Reputation: 16
I've got a list of several Restaurants in an NSArray and I want to copy the ones that are the closest to my location into an NSMutableArray and order them... I have the following code
@property(strong, nonatomic) NSArray *restaurants;
@property(strong, nonatomic) NSMutableArray *orderedRestaurants;
-(void) orderRestaurants{
for(RestaurantBranch *restaurant in _restaurants){
if([self getDistance:restaurant]<10){
[_orderedRestaurants addObject:restaurant];
}
}
}
but I can't find an efficient way to order the NSMutableArray by the calculated distance
Upvotes: 0
Views: 50
Reputation: 8014
You can copy the original array into your sorted array then sort it by distance for each entry relative to `self'.
In the code I assumed distance was a float. Use whataver type your distance is defined as.
- (void) orderRestaurants{
self.orderedRestaurants=[self.restaurants mutableCopy];
[self.orderedRestaurants sortUsingComparator:^NSComparisonResult(id a, id b) {
NSComparisonResult result=NSOrderedSame;
float distancea=[self getDistance:(RestaurantBranch *)a];
float distanceb=[self getDistance:(RestaurantBranch *)b];
if (distancea < distanceb){
result = NSOrderAscending;
}
else if (distanceb < distancea){
result = NSOrderDescending;
}
return result;
}];
}
The result is the original array of branches sorted by distance.
This will calculate the distance multiple times. You could look to cache the distances depending on how complicated your distance calculation is.
Upvotes: 2