I need to show a list of products sorted by distance to the nearest address of that product's compa开发者_如何学Pythonny.
I have a cord data structure like so:
Product <<-> Company <->> Addresses
The address
entity has an NSNumber field for both latitude and longitude.
I also have a shared Singleton that fetches and stores the current CLLocation
.
What is the best strategy for fetching and sorting this.
Method 1
Add a readonly distance
property to the Address entity that creates a CLLocation out of the lat/lng properties and returns the calculated distance between that and the stored currentLocation from the shared singleton. This could have the benefit of letting me use NSPredicate for sorting and filtering. I'm wondering if it would have performance costs though.
Method 2
Just fetch all of the products into an array and loop through the array to sort it manually.
When I did this, I used this in the singleton:
- (NSNumber*) distanceToLocation:(CLLocationCoordinate2D) location{
if (!self.isValidLocation) return nil;
CLLocation *loc = [[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude];
CLLocationDistance distance=[self.locationManager.location distanceFromLocation:loc];
return [NSNumber numberWithDouble:distance];
}
Then the readonly property of the address entity calls it.
精彩评论