等到第一个异步功能完成后再执行第二个异步功能

时间:2015-10-10 19:30:48

标签: ios swift

我希望在第二个异步函数被调用之前完成第一个异步函数

我试过这个:

  <div class="label">
<p>above we have family, species, vernacular name...</p>
<div class="distribution">Northern South America, Northern Argentina, Panamá, Costa Rica, Costa Rica, Costa Rica, Costa Rica, Costa <div class="code2">0G 1968GR01496.1</div>Rica</div>
</div>

但它们都在同一时间运行

2 个答案:

答案 0 :(得分:2)

你有很多选择。以下是一些:

1。使用您自己的串行调度队列:

let queue = dispatch_queue_create("com.mycompany.serial-queue",
    dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0))

dispatch_async(queue) {
    print("inside block 1")
}

dispatch_async(queue) {
    print("inside block 2")
}

2。将NSOperationQueue与依赖项一起使用:

let queue = NSOperationQueue()

let op1 = NSBlockOperation {
    print("inside block 1")
}

let op2 = NSBlockOperation {
    print("inside block 2")
}

op2.addDependency(op1) // op2 may only execute after op1 is finished

queue.addOperation(op1)
queue.addOperation(op2)

3。使用序列号NSOperationQueue:

let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1 // execute 1 operation at a time

queue.addOperationWithBlock {
    print("inside block 1")
}

queue.addOperationWithBlock {
    print("inside block 2")
}

答案 1 :(得分:1)

重构您的LoadFirst方法(应该称为loadFirst btw)以获取完成块并在异步任务完成后调用它。然后将完成块中的loadSecond调用传递给loadFirst。