1

So, I have array(fetch result from Core Data). I want iterate it, and for each element of the array (url, and other data) create a new parallel task (network). Only after completing all these tasks need to start a new parallel task.

Tell me how to make it? Serial Queue? Dispatch queue?

Vladislav
  • 165
  • 1
  • 5
  • 15

2 Answers2

1

A fun way that I have done this is to use dispatch_group_t. You can say:

dispatch_group_t myGroup = dispatch_group_create();

Then for each operation you will need to track call:

dispatch_group_enter(myGroup);

Inside of your completion blocks call this as the last line of your completion block:

dispatch_group_leave(myGroup);

Finally, call:

dispatch_group_notify(myGroup, dispatch_get_main_queue(), ^{ // kick off tasks after the number of dispatch_group_leave(myGroup) calls // equal the number of dispatch_group_enter(myGroup) calls });

This was a challenging problem for me in an app I am currently working on and this worked like a charm. Some things to note: Make sure you don't call enter more than leave otherwise notify will never be called. Also, your application will crash if you call leave too many times as you will be referencing a group that has been already notified and therefore released. I usually prevent this by calling enter inside a separate loop before kicking off the network tasks that have the leave calls in their completion. This may not be necessary, but it makes me feel more secure that all my enters are called before any leaves, therefore the number of enters and leaves are never equal before the last completion. Cheers!

dotToString
  • 230
  • 2
  • 13
  • Instead of calling `enter` and `leave` manually, you can call `dispatch_group_async` with a block to perform, and it will call them for you. – Léo Natan Apr 19 '14 at 04:08
0

Use enumerateObjectsWithOptions:usingBlock: and pass option NSEnumerationConcurrent.

valfer
  • 3,545
  • 2
  • 19
  • 24
  • This won't work because the OP wants to delay the next enumeration until the network task completes. Essentially they want async enumerate. – malhal Mar 23 '16 at 12:26