Last active
September 19, 2018 16:50
-
-
Save aChase55/3bc4863ef74c65cc483358f738d953da to your computer and use it in GitHub Desktop.
An Operation subclass that does work asynchronously
This file contains 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 AsyncOperation: Operation { | |
private var _isFinished: Bool = false | |
private var _isExecuting: Bool = false | |
open func execute() { assertionFailure("Overide execute() in subclass") } | |
override var isAsynchronous: Bool { return true } | |
override var isConcurrent: Bool { return true } | |
override var isFinished: Bool { return _isFinished } | |
override var isExecuting: Bool { return _isExecuting } | |
final override func start() { | |
guard !isCancelled else { | |
willChangeValue(forKey: "isFinished") | |
_isFinished = true | |
didChangeValue(forKey: "isFinished") | |
return | |
} | |
willChangeValue(forKey: "isExecuting") | |
Thread.detachNewThreadSelector(#selector(main), toTarget: self, with: nil) | |
_isExecuting = true | |
didChangeValue(forKey: "isExecuting") | |
} | |
final override func main() { execute() } | |
//Call completeOperation() within your overriden execute method when work is completed | |
final func completeOperation() { | |
willChangeValue(forKey: "isFinished") | |
willChangeValue(forKey: "isExecuting") | |
_isExecuting = false | |
_isFinished = true | |
didChangeValue(forKey: "isExecuting") | |
didChangeValue(forKey: "isFinished") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment