
This video is only available to subscribers. Start a subscription today to get access to this and 470 other videos.
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.
This episode is part of a series: Deep Dive with NSOperation.
1. NSOperation Basics 17 min |
2. Asynchronous Operations 17 min |
3. NSOperation Dependencies 11 min |
4. Advanced NSOperations 14 min |
Episode Links
- Source Code
- NSOperation Class Reference
- NSOperationQueue Class Reference
- Concurrency Programming Guide
- Advanced NSOperation talk at WWDC
- NSByteCountFormatter Class Reference
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
}
}