One way to do this is to use GCD to split the job and send it to the parallel queue using the send group. Then you can use dispatch_group_notify()to do something with the work when all parallel work units have been completed. This will support your application while doing the work. After sub-units of work are performed, the results are sent back to the main queue (which is the user interface queue) for aggregation.
You should read this too: https://mikeash.com/pyblog/friday-qa-2009-09-25-gcd-practicum.html
Here is a sample code that I worked with very quickly:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
const NSUInteger count = 100;
const NSUInteger workUnitCount = 4;
const NSUInteger countPerWorkUnit = count / workUnitCount;
dispatch_group_t numberGroup = dispatch_group_create();
dispatch_queue_t numberQueue = dispatch_queue_create("numberQueue", DISPATCH_QUEUE_CONCURRENT);
NSMutableArray *__block results = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < workUnitCount; ++i) {
dispatch_group_async(numberGroup, numberQueue, ^{
NSMutableArray *workUnitResults = [NSMutableArray arrayWithCapacity:workUnitCount];
for (int i = 0; i < countPerWorkUnit; ++i) {
[workUnitResults addObject:@(arc4random() % 5000)];
}
dispatch_async(dispatch_get_main_queue(), ^{
[results addObjectsFromArray:workUnitResults];
});
});
}
dispatch_group_notify(numberGroup, dispatch_get_main_queue(), ^{
[results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"random result #%@: %@", @(idx), results[idx]);
}];
});
return YES;
}
source
share