Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Asynchronous NSBlockOperation
import Foundation
class AsyncBlockOperation: NSOperation {
typealias Block = (Void -> Void) -> Void
private let block: Block
private var _executing = false
private var _finished = false
init(block: Block) {
self.block = block
super.init()
}
override func start() {
guard (self.executing || self.cancelled) == false else { return }
self.executing = true
self.block(finish)
}
private func finish() {
self.executing = false
self.finished = true
}
override var asynchronous: Bool {
return true
}
override var executing: Bool {
get { return _executing }
set {
let key = "isExecuting"
willChangeValueForKey(key)
_executing = newValue
didChangeValueForKey(key)
}
}
override var finished: Bool {
get { return _finished }
set {
let key = "isFinished"
willChangeValueForKey(key)
_finished = newValue
didChangeValueForKey(key)
}
}
}

You should put all accesses to _executing and _finished inside a queue so that your -start and -finish methods can be thread safe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment