Skip to content

Instantly share code, notes, and snippets.

@tomkowz
Created May 9, 2017 06:48
Show Gist options
  • Save tomkowz/2734cf25318b7cfcd475b1149ab3ee7a to your computer and use it in GitHub Desktop.
Save tomkowz/2734cf25318b7cfcd475b1149ab3ee7a to your computer and use it in GitHub Desktop.
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)
}
}
}
@hborders
Copy link

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