Skip to content

Instantly share code, notes, and snippets.

@coryhymel
Last active January 4, 2016 04:29
Show Gist options
  • Save coryhymel/8568981 to your computer and use it in GitHub Desktop.
Save coryhymel/8568981 to your computer and use it in GitHub Desktop.
GCD Semaphore for finding items around you based on distance
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))];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment