Swift – Concurrency, NSOperation, NSOperationQueue

Swift – Concurrency, NSOperation, NSOperationQueue

Written by: Debasis Das (21-Jan-2015)

Details about Concurrency, NSOperation, Operation Queue & Grand Central Dispatch can be found in this article. The concepts remain the same, there is a slight change to  implementation.

NSInvocationOperation is not present in Swift as opposed to Objective C

Swift NSBlockOperation – Sample Code 1

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        self.blockOperationsTest1()
    }
    
    func blockOperationsTest1(){

        var operationQueue = NSOperationQueue()
        
        let operation1 : NSBlockOperation = NSBlockOperation ({
            self.doCalculations()
            
            let operation2 : NSBlockOperation = NSBlockOperation ({
            
                self.doSomeMoreCalculations()
                
            })
            operationQueue.addOperation(operation2)
        })
        operationQueue.addOperation(operation1)
    }
    
    func doCalculations(){
        NSLog("do Calculations")
        for i in 100...105{
            println("i in do calculations is \(i)")
            sleep(1)
        }
    }

    func doSomeMoreCalculations(){
        NSLog("do Some More Calculations")
        for j in 1...5{
            println("j in do some more calculations is \(j)")
            sleep(1)
        }

    }

Output:
2015-04-07 01:49:35.953 SwiftBlockOperations[6740:241502] do Calculations
i in do calculations is 100
i in do calculations is 101
i in do calculations is 102
i in do calculations is 103
i in do calculations is 104
i in do calculations is 105
2015-04-07 01:49:41.966 SwiftBlockOperations[6740:241534] do Some More Calculations
j in do some more calculations is 1
j in do some more calculations is 2
j in do some more calculations is 3
j in do some more calculations is 4
j in do some more calculations is 5

Swift Creating NSBlockOperation – Sample Code 2

    func sampleCodeOne (){
        var operationQueue: NSOperationQueue = NSOperationQueue.mainQueue()
        var completionBlockOperation: NSBlockOperation = NSBlockOperation.init(
            {
                println("completion Block is getting called")
            }
        )
    
        var workerBlockOperation:NSBlockOperation = NSBlockOperation.init(
            {
                println("worker block")
                self.sampleCodeOneWorkerMethod()
            }
        )
        completionBlockOperation.addDependency(workerBlockOperation)
        operationQueue.addOperation(workerBlockOperation)
        operationQueue.addOperation(completionBlockOperation)
    }
    
    func sampleCodeOneWorkerMethod ()
    {
        println("Actual Worker Block")
        for (var i = 0; i<5; i++)
        {
            sleep(1)
            println(i)
        }
        
    }

Swift – Creating Custom NSOperation

    
    func sampleCodeTwo(){
        let customOperation : MyCustomOperation = MyCustomOperation()
        
        customOperation.completionBlock = {
            println("Both the Block Operation and the Custom Operation is completed")
        }

        var workerBlockOperation:NSBlockOperation = NSBlockOperation.init(
            {
                println("Primary Worker block")
            }
        )
        customOperation.addDependency(workerBlockOperation)

        let operationQueue = NSOperationQueue.mainQueue()
        operationQueue.addOperation(customOperation)
        operationQueue.addOperation(workerBlockOperation)
    }
}

/*******************************************/
//CUSTOM SWIFT NSOPERATION CLASS
/*******************************************/

class MyCustomOperation: NSOperation{
    var isExecuting = false;
    var isFinished = false;
    
    override func main() {
        if self.cancelled {
            return
        }
        else
        {
            NSLog("custom operation work is done here.")
            for (var i = 0; i<5; i++)
            {
                NSLog("i%d",i)
                sleep(1)
            }
        }
        self.willChangeValueForKey("executing")
        isExecuting = false
        self.didChangeValueForKey("executing")

        self.willChangeValueForKey("finished")
        isFinished = true
        self.didChangeValueForKey("finished")
        
        if(finished)
        {
            NSLog("completed")
        }
        else
        {
            NSLog("Not completed")
        }
    }
}
Posted in Cocoa, iOS, Objective C, Swift Tagged with: , , ,
2 comments on “Swift – Concurrency, NSOperation, NSOperationQueue
  1. Lydia says:

    So in swift2 which one is preferable Grand Central Dispatch or Nsoperationqueue for fetching data from cloud in background and update tableview.

    • Debasis Das says:

      Would prefer NSOperationQueue, its a more high level implementation and allows you to create your own custom operations. Allows cancelling of operations as well.
      I use GCD when I need a quicker implementation

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news