-
-
Save ddeville/5228224 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@interface RetrievalOperation : NSOperation | |
+ (id)retrievalOperationWithBlock:(id (^)(void))block; | |
@property (readonly, strong, nonatomic) id result; | |
@end | |
@interface RetrievalOperation (/* Private */) | |
@property (readwrite, strong, nonatomic) id result; | |
@property (copy, nonatomic) id (^block)(void); | |
@end | |
@implementation RetrievalOperation | |
+ (id)retrievalOperationWithBlock:(id (^)(void))block | |
{ | |
RetrievalOperation *operation = [[self alloc] init]; | |
[operation setBlock:block]; | |
return operation; | |
} | |
- (void)main | |
{ | |
id result = [self block](); | |
[self setResult:result]; | |
} | |
@end | |
int main(int argc, const char **argv) | |
{ | |
@autoreleasepool { | |
id databaseClient; // some database client object | |
NSArray *fileURLs; // some file URLs from somewhere else | |
NSPredicate *predicate; // some predicate from somewhere else | |
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init]; | |
RetrievalOperation *databaseRetrievalOperation = [RetrievalOperation retrievalOperationWithBlock:^ id (void) { | |
return [databaseClient fetchObjectsMatchingPredicate:predicate]; | |
}]; | |
[backgroundQueue addOperation:databaseRetrievalOperation]; | |
NSMutableArray *fileRetrievalOperations = [NSMutableArray array]; | |
for (NSURL *fileURL in fileURLs) { | |
RetrievalOperation *fileRetrievalOperation = [RetrievalOperation retrievalOperationWithBlock:^ id (void) { | |
return [NSData dataWithContentsOfURL:fileURL]; | |
}]; | |
[fileRetrievalOperations addObject:fileRetrievalOperation]; | |
[backgroundQueue addOperation:fileRetrievalOperation]; | |
} | |
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^ { | |
NSArray *databaseObjects = [databaseRetrievalOperation result]; | |
NSMutableArray *fileContents = [NSMutableArray array]; | |
for (RetrievalOperation *fileRetrievalOperation in fileRetrievalOperations) { | |
[fileContents addObject:[fileRetrievalOperation result]]; | |
} | |
[self finishProcessingDatabaseObjects:databaseObjects fileContents:fileContents]; | |
}]; | |
[completionOperation addDependency:databaseRetrievalOperation]; | |
for (NSOperation *fileRetrievalOperation in fileRetrievalOperations) { | |
[completionOperation addDependency:fileRetrievalOperation]; | |
} | |
[[NSOperationQueue mainQueue] addOperation:completionOperation]; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment