NSOperation Basics

Episode #175 | 17 minutes | published on June 26, 2015
Subscribers Only
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: {
 operation.completionBlock = {
    println("Done executing")

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 {

            println("Sleeping \(i)...")

        if cancelled {

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

        self.fileSystemAttributes = attribs
blog comments powered by Disqus