-
-
Save embassem/e7fbbf9ea8a43081bce89e0279938352 to your computer and use it in GitHub Desktop.
Subclass of NSOperation to make it asynchronous in Swift 3
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
// | |
// AsynchronousOperation.swift | |
// | |
// Created by Vasily Ulianov on 09.02.17. | |
// Copyright © 2017 Vasily Ulianov. All rights reserved. | |
// | |
import Foundation | |
/// Subclass of `Operation` that add support of asynchronous operations. | |
/// ## How to use: | |
/// 1. Call `super.main()` when override `main` method, call `super.start()` when override `start` method. | |
/// 2. When operation is finished or cancelled set `self.state = .finished` | |
class AsynchronousOperation: Operation { | |
override var isAsynchronous: Bool { return true } | |
override var isExecuting: Bool { return state == .executing } | |
override var isFinished: Bool { return state == .finished } | |
var state = State.ready { | |
willSet { | |
willChangeValue(forKey: state.keyPath) | |
willChangeValue(forKey: newValue.keyPath) | |
} | |
didSet { | |
didChangeValue(forKey: state.keyPath) | |
didChangeValue(forKey: oldValue.keyPath) | |
} | |
} | |
enum State: String { | |
case ready = "Ready" | |
case executing = "Executing" | |
case finished = "Finished" | |
fileprivate var keyPath: String { return "is" + self.rawValue } | |
} | |
override func start() { | |
if self.isCancelled { | |
state = .finished | |
} else { | |
state = .ready | |
main() | |
} | |
} | |
override func main() { | |
if self.isCancelled { | |
state = .finished | |
} else { | |
state = .executing | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment