Skip to content

Instantly share code, notes, and snippets.

@epologee
Created February 8, 2014 21:34
Show Gist options
  • Save epologee/8890692 to your computer and use it in GitHub Desktop.
Save epologee/8890692 to your computer and use it in GitHub Desktop.
Thread locking category method on ALAssetsLibrary, to illustrate how to block background threads until the assets library method finishes
#import <Foundation/Foundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface ALAssetsLibrary (EEEConcurrency)
- (NSUInteger)eee_enumerateGroupsLockedWithTypes:(ALAssetsGroupType)types
usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock
failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock;
@end
#import "ALAssetsLibrary+EEEConcurrency.h"
@implementation ALAssetsLibrary (EEEConcurrency)
- (NSUInteger)eee_enumerateGroupsLockedWithTypes:(ALAssetsGroupType)types
usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock
failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock
{
NSAssert(![NSThread isMainThread], @"This would create a deadlock (main thread waiting for main thread to complete)");
enum
{
EEEAssetsLibraryDone,
EEEAssetsLibraryBusy
};
NSConditionLock *assetsLibraryConditionLock = [[NSConditionLock alloc] initWithCondition:EEEAssetsLibraryBusy];
__block NSUInteger numberOfGroups = 0;
[self enumerateGroupsWithTypes:types
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
enumerationBlock(group, stop);
if (group) numberOfGroups++;
if (!group || *stop)
{
[assetsLibraryConditionLock lock];
[assetsLibraryConditionLock unlockWithCondition:EEEAssetsLibraryDone];
}
}
failureBlock:^(NSError *error) {
failureBlock(error);
[assetsLibraryConditionLock lock];
[assetsLibraryConditionLock unlockWithCondition:EEEAssetsLibraryDone];
}];
[assetsLibraryConditionLock lockWhenCondition:EEEAssetsLibraryDone];
[assetsLibraryConditionLock unlock];
return numberOfGroups;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment