如何在GCD中的NSOperationQueue之类的操作之间添加依赖项

时间:2018-09-30 09:31:59

标签: ios swift

以下是这4个操作,它们使用NSOperation队列加载了4张图像。这里的操作2取决于操作1,操作3取决于操作2。

有人知道我可以在GCD中实现同样的目标吗?

@IBAction func didClickOnStart(sender: AnyObject) {

        queue = NSOperationQueue()
        let operation1 = NSBlockOperation(block: {
            let img1 = Downloader.downloadImageWithURL(imageURLs[0])
            NSOperationQueue.mainQueue().addOperationWithBlock({
                self.imageView1.image = img1
            })
        })

        operation1.completionBlock = {
            print("Operation 1 completed")
        }
        queue.addOperation(operation1)

        let operation2 = NSBlockOperation(block: {
            let img2 = Downloader.downloadImageWithURL(imageURLs[1])
            NSOperationQueue.mainQueue().addOperationWithBlock({
                self.imageView2.image = img2
            })
        })

        operation2.completionBlock = {
            print("Operation 2 completed")
        }
        queue.addOperation(operation2)


        let operation3 = NSBlockOperation(block: {
            let img3 = Downloader.downloadImageWithURL(imageURLs[2])
            NSOperationQueue.mainQueue().addOperationWithBlock({
                self.imageView3.image = img3
            })
        })

        operation3.completionBlock = {
            print("Operation 3 completed")
        }
        queue.addOperation(operation3)

        let operation4 = NSBlockOperation(block: {
            let img4 = Downloader.downloadImageWithURL(imageURLs[3])
            NSOperationQueue.mainQueue().addOperationWithBlock({
                self.imageView4.image = img4
            })
        })

        operation4.completionBlock = {
            print("Operation 4 completed")
        }
        queue.addOperation(operation4)
    }

在这里我们可以在操作之间添加依赖项

operation2.addDependency(operation1)
operation3.addDependency(operation2)

1 个答案:

答案 0 :(得分:0)

您不能(或者只是不这样做,因为它比使用OperationQueueOperation子类要花更多的时间)。