最良のオプションは、多くのデータベースの組み込み機能を使用して、フィルタリングと順序付けを行うことです。
基本的な実装は非常に明白です。店舗を並べ替えて、定義された領域内にある最初の 25 を取得するだけです。
これは、何千もの店舗がある場合に最適化されたバージョンの書き方です。
NSArray *stores = ...;
CLLocation *myLocation = ...;
NSMutableArray *nearestStores = [NSMutableArray array];
CLRegion *nearest100kmRegion = [CLRegion initCircularRegionWithCenter:[myLocation coordinate]
radius:100000
identifier:@"someIdentifier"];
// We will need to enumerate all stores to ensure that there are no more
// than 25 objects within the defined region.
//
// Since there may be thousands of objects and many of them can be
// out of the defined region, we should perform concurrent enumeration
// for performance reasons.
dispatch_semaphore s = dispatch_semaphore_create(1);
[stores enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id store, NSUInteger idx, BOOL *stop)
{
if ([nearest100kmRegion containsCoordinate:[[store location] coordinate]])
{
dispatch_semaphore_wait(s, DISPATCH_FOREVER);
[nearestStores addObject:store];
dispatch_semaphore_signal(s);
}
}];
dispatch_release(s);
if ([nearestStores count] > 25)
{
[nearestStores sortWithOptions:NSSortConcurrent
usingComparator:^(id store1, id store2)
{
return [myLocation distanceFromLocation:[store1 location]] - [myLocation distanceFromLocation:[store2 location]];
}];
}
return [nearestStores subarrayWithRange:NSMakeRange(0, MAX([nearestStores count], 25))];