Rinto Andrews Rinto Andrews - 3 months ago 17
iOS Question

how adddependency method works in NSOperationQueue

i am testing NSoperationqueue

queue = NSOperationQueue()
let operation1 = NSBlockOperation(block: {
let img1 = NSData(contentsOfURL: self.img1)
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imgs1.image = UIImage(data: img1!)

})
})

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




let operation2 = NSBlockOperation(block: {
let img2 = NSData(contentsOfURL: self.img2)
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imgs2.image = UIImage(data: img2!)

})
})



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

let operation3 = NSBlockOperation(block: {
let img3 = NSData(contentsOfURL: self.img3)
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imgs3.image = UIImage(data: img3!)

})
})

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

operation3.addDependency(operation1)

}


the result is


Operation 3 completed

Operation 1 completed

Operation 2 completed


can you please explain addDependency works

it should work like operation 1 should complete first ?

how to execute one after other ?

how to create dependency ?

Answer

you can use it :

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

operation3 will start when operation2 be completed and operation2 will start when operation1 be completed .

notice : operation1 should be completed until operation2 will start

queue = NSOperationQueue()
    let operation1 = NSBlockOperation(block: {
        let img1 = NSData(contentsOfURL: self.img1)
        NSOperationQueue.mainQueue().addOperationWithBlock({
            self.imgs1.image = UIImage(data: img1!)

        })
    })

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


    let operation2 = NSBlockOperation(block: {
        let img2 = NSData(contentsOfURL: self.img2)
        NSOperationQueue.mainQueue().addOperationWithBlock({
            self.imgs2.image = UIImage(data: img2!)

        })
    })



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

    let operation3 = NSBlockOperation(block: {
        let img3 = NSData(contentsOfURL: self.img3)
        NSOperationQueue.mainQueue().addOperationWithBlock({
            self.imgs3.image = UIImage(data: img3!)

        })
    })

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

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

    queue.addOperation(operation1)
    queue.addOperation(operation2)
    queue.addOperation(operation3)


}