Created
May 9, 2017 06:48
-
-
Save tomkowz/2734cf25318b7cfcd475b1149ab3ee7a to your computer and use it in GitHub Desktop.
Asynchronous NSBlockOperation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should put all accesses to
_executing
and_finished
inside a queue so that your-start
and-finish
methods can be thread safe.