开发者

Creating Dependencies Within An NSOperation

I have a fairly involved download process I want to perform in a background thread. There a开发者_运维知识库re some natural dependencies between steps in this process. For example, I need to complete the downloads of both Table A and Table B before setting the relationships between them (I'm using Core Data).

I thought first of putting each dependent step in its own NSOperation, then creating a dependency between the two operations (i.e. download the two tables in one operation, then set the relationship between them in the next, dependent operation). However, each NSOperation requires it's own NSManagedContext, so this is no good. I don't want to save the background context until both tables have been downloaded and their relationships set.

I've therefore concluded this should all occur inside one NSOperation, and that I should use notifications or some other mechanism to call the dependent method when all the conditions for running it have been met.

I'm an iOS beginner, however, so before I venture down this path, I wouldn't mind advice on whether I've reached the right conclusion.


Given your validation requirements, I think it will be easiest inside of one operation, although this could turn into a bit of a hairball as far as code structure goes.

You'll essentially want to make two wire fetches to get the entire dataset you require, then combine the data and parse it at one time into Core Data.

If you're going to use the asynchronous API's this essentially means structuring a class that waits for both operations to complete and then launches another NSOperation or block which does the parse and relationship construction.

Imagine this order of events:

  1. User performs some action (button tap, etc.)
  2. Selector for that action fires two network requests
  3. When both requests have finished (they both notify a common delegate) launch the parse operation

Might look something like this in code:

- (IBAction)someAction:(id)sender {
    //fire both network requests
    request1.delegate = aDelegate;
    request2.delegate = aDelegate;
 }

 //later, inside the implementation of aDelegate
 - (void)requestDidComplete... {
   if (request1Finished && request2Finished) {
       NSOperation *parse = //init with fetched data
       //launch on queue etc.
   }
 }

There's two major pitfalls that this solution is prone to:

  1. It keeps the entire data set around in memory until both requests are finished
  2. You will have to constantly switch on the specific request that's calling your delegate (for error handling, success, etc.)

Basically, you're implementing operation dependencies on your own, although there might not be a good way around that because of the structure of NSURLConnection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜