Created
February 8, 2014 21:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#import <AssetsLibrary/AssetsLibrary.h> | |
@interface ALAssetsLibrary (EEEConcurrency) | |
- (NSUInteger)eee_enumerateGroupsLockedWithTypes:(ALAssetsGroupType)types | |
usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock | |
failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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