0

So the task is the following: 1)I have a track ID, I need to ask the server for all the track data 2)parse response (here I also have an album ID) 3)now I have an album ID, I need to ask the server for all the album data 4)parse response (here I also have an artist ID) 5)now I have an artist ID, I need to ask the server for all the artist data

I wonder what is the right way to do this with gcd. 3 dispatch_sync-s inside dispatch_async? I want all this to be one operation, run in the background, so at first I thought about NSOperation, but all callbacks, parsing, saving to core data need to happen on background thread, so I'd have to create a separate run loop for callbacks to make sure it will not be killed before I get a response and will not block ui.

so the question is how should I use gcd here, or is it better to go with nsoperation and a runloop thread for callbacks? thanks

bdash
  • 18,110
  • 1
  • 59
  • 91
dariaa
  • 6,285
  • 4
  • 42
  • 58
  • 1
    GCD does NOT guarantee operation on a single background thread. GCD queue's are just a list of operations to perform, NOT a thread to perform them on. It will divide the task into multiple threads as it sees fit. – borrrden Apr 10 '12 at 07:57

1 Answers1

1

I would suggest using NSOperation and callbacks executed on the main thread.

If you think about it, your workflow is pretty sequential: 1 -> 3 -> 5; the parsing steps (2 and 4) are not presumably that expensive so that you want to execute them on a separate thread (I guess they are not expensive at all and you can disregard parsing time compared to waiting time for network communication).

Furthermore, if you use a communication framework like AFNetworking (or even NSURLConnection + blocks) your workflow will be pretty easy to implement:

  1. retrieve track data
  2. in "retrieve track data" response handler, get album id, then send new request for "album data";
  3. in "retrieve album data" response handler, get artist id, and so on...
sergio
  • 68,819
  • 11
  • 102
  • 123
  • I don't think you even need `NSOperation`. Provided the asynchronous methods of `NSURLConnection` are used, why not do everything on the main thread. – JeremyP Apr 10 '12 at 09:53