Episode #175

NSOperation Basics

Series: Deep Dive with NSOperation

17 minutes
Published on June 26, 2015

This video is only available to subscribers. Get access to this video and 584 others.

In this episode we take a look at the basics of NSOperation, NSOperationQueue, starting from block operations and moving to custom NSOperation subclasses. We'll also see why it's important to make your operations thread safe.

Episode Links

Creating an operation queue

 let operationQueue = NSOperationQueue()
 operationQueue.maxConcurrentOperationCount = 1  // makes this a serial queue

 operationQueue.suspended = true // use this if you don't want to automatically execute operations as they are added.

Adding a block operation

 let operation = NSBlockOperation(block: {
    println("executing")
 })
 operation.completionBlock = {
    println("Done executing")
 }
 operationQueue.addOperation(operation)

Creating an operation subclass

class FreeSpaceOperation : NSOperation {
    var fileSystemAttributes: NSDictionary?
    var error: NSError?

    let path: String

    init(path: String) {
        self.path = path
    }

    override func main() {
        let fileManager = NSFileManager.defaultManager()

        for i in reverse(1...5) {
            if cancelled {
                return
            }

            println("Sleeping \(i)...")
            sleep(1)
        }

        if cancelled {
            return
        }

        let attribs = fileManager.attributesOfFileSystemForPath(path, error: &error)
        println("attribs for \(path): \(attribs)")

        self.fileSystemAttributes = attribs
    }
}