First, I suggest you to use a DTO. Something like this:
@interface Place : NSObject
@property(nonatomic, strong) NSString * name;
@property(nonatomic, strong) CLLocationCoordinate2D * coord;
@end
Then use a DAO to get all the places in an NSArray
like Anna Karenina suggest you.
@interface PlaceDAO : NSObject
- (NSArray *) places;
- (id) sharedInstance;
@end
Finally you can sort with that:
1. Create a Category of CLLocation to calculate what coord is nearest to a reference coord.
//CLLocation+DistanceComparison.h
static CLLocation * referenceLocation;
@interface CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other;
@end
//CLLocation+DistanceComparison.m
@implementation CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other {
CLLocationDistance thisDistance = [self distanceFromLocation:referenceLocation];
CLLocationDistance thatDistance = [other distanceFromLocation:referenceLocation];
if (thisDistance < thatDistance) { return NSOrderedAscending; }
if (thisDistance > thatDistance) { return NSOrderedDescending; }
return NSOrderedSame;
}
@end
2. Add a compare method to your Place DAO.
- (NSComparisonResult)compare:(Place *)otherObject { return [self.coord compareToLocation:otherObject.coord]; }
3. Finally sort the array like this.
NSArray * places = [[PlacesDAO sharedInstance] places]; referenceLocation = userLocation; NSArray * mySortedPlaces = [places sortedArrayUsingSelector:@selector(compare:)]; referenceLocation = nil;
Don't forget add include the category.