Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. for(NSInteger i = 0; i < 10; i++) {
  2. // enqueue operation in queue
  3. dispatch_async(queue, ^{
  4. // create semaphore
  5. dispatch_semaphore_t sema = dispatch_semaphore_create(0);
  6.  
  7. // do something async, I do use another dispatch_queue for example
  8. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  9. // wrap in autoreleasepool to release memory upon completion
  10. // in your case wrap the resultBlock in autoreleasepool
  11. @autoreleasepool {
  12. // here for example the nested operation sleeps for two seconds
  13. sleep(2);
  14.  
  15. // add the operation result to array
  16. // I construct an array of strings for example
  17. [results addObject:[NSString stringWithFormat:@"Operation %d has finished.", i]];
  18.  
  19. // signal that nested async operation completed
  20. // to wake up dispatch_semaphore_wait below
  21. dispatch_semaphore_signal(sema);
  22. }
  23. });
  24.  
  25. // wait until the nested async operation signals that its finished
  26. dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  27.  
  28. NSLog(@"Finished single operation.");
  29. });
  30. }
  31.  
  32. // will be called once all operations complete
  33. dispatch_async(queue, ^{
  34. NSLog(@"Finished all jobs.");
  35. NSLog(@"Results: %@", results);
  36. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement