Learning NSBlockOperation

前端 未结 3 1572
滥情空心
滥情空心 2021-01-30 18:05

I\'m a big fan of blocks, but have not used them for concurrency. After some googling, I pieced together this idea to hide everything I learned in one place. The goal is to ex

3条回答
  •  臣服心动
    2021-01-30 18:50

    You should not be creating a new NSOperationQueue for each executeBlock:completion: call. This is expensive and the user of this API has no control over how many operations can execute at a time.

    If you are returning NSOperation instances then you should leave it up to the caller to decide which queue to add them to. But at that point, your method really isn't doing anything helpful and the caller might as well create the NSBlockOperation themselves.

    If you just want a simple and easy way to spin off a block in the background and perform some code when it finishes, you're probably better off making some simple GCD calls with the dispatch_* functions. For example:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // do your background work
        // ...
    
        // now execute the 'completion' code.
        // you often want to dispatch back to the main thread to update the UI
        // For example:
    
        dispatch_async(dispatch_get_main_queue(), ^{
            // update UI, etc.
            myLabel.text = @"Finished";
        });
    
    });
    

提交回复
热议问题