您是否可以为NSOperation对象使用跨队列依赖项?

时间:2016-12-05 20:58:24

标签: swift dependencies nsoperation nsoperationqueue

是否可以/合法地进行跨队列依赖操作?

考虑以下内容......

let operationA = NSBlockOperation(block: someBlock)
let operationB = NSBlockOperation(block: someOtherBlock)

let operationC = NSBlockOperation(block: finalBlock)
operationC.addDependency(operationA)
operationC.addDependency(operationB)

OperationQueue().addOperation(operationC)
OperationQueue().addOperation(operationA)
OperationQueue().addOperation(operationB)

我在文档中的任何地方都没有看到这是一种限制用法,但我也不确定这样的事情是否可行/支持。 (注意:我也不是说这是不是很好的做法。只是试着用语言来看看什么可能作为思考的食物。)

1 个答案:

答案 0 :(得分:1)

"关于依赖关系的另一个好处是它们不受操作队列的限制。现在,我的意思是什么?如果应用程序中有两个操作队列,则第一个队列中的操作可能取决于第二个队列中的操作。"

https://developer.apple.com/videos/play/wwdc2015/226/

以下是您可以尝试的示例:

    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];

NSBlockOperation *a1 = [[NSBlockOperation alloc] init];

NSBlockOperation *a2 = [[NSBlockOperation alloc] init];

[a1 addExecutionBlock:^{
    NSLog(@"a1");

    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];

    NSBlockOperation *b1 = [[NSBlockOperation alloc] init];

    NSBlockOperation *b2 = [[NSBlockOperation alloc] init];

    [b1 addExecutionBlock:^{
        NSLog(@"b1");
    }];

    [b2 addExecutionBlock:^{
        NSLog(@"b2");
    }];

    [a2 addDependency:b2]; // makes this inner queue finish first

    [b2 addDependency:b1];

    [queue2 addOperations:@[b1, b2] waitUntilFinished:NO];

}];

[a2 addExecutionBlock:^{
    NSLog(@"a2");
}];

[a2 addDependency:a1];

[queue1 addOperations:@[a1, a2] waitUntilFinished:NO];

输出:

2017-01-08 00:27:03.019497 OpTest[26141:36238589] a1
2017-01-08 00:27:03.019621 OpTest[26141:36238621] b1
2017-01-08 00:27:03.019721 OpTest[26141:36238589] b2
2017-01-08 00:27:03.019773 OpTest[26141:36238621] a2

如您所见,[a2 addDependency:b2]行允许操作的子队列在主队列中完成。