-
-
Save pruinis/13be23760eed698b82c34728035e533b to your computer and use it in GitHub Desktop.
Concurrent NSOperation in Swift
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
// | |
// ConcurrentOperation.swift | |
// | |
// Created by Caleb Davenport on 7/7/14. | |
// | |
// Learn more at http://blog.calebd.me/swift-concurrent-operations | |
// | |
import Foundation | |
class ConcurrentOperation: NSOperation { | |
// MARK: - Types | |
enum State { | |
case Ready, Executing, Finished | |
func keyPath() -> String { | |
switch self { | |
case Ready: | |
return "isReady" | |
case Executing: | |
return "isExecuting" | |
case Finished: | |
return "isFinished" | |
} | |
} | |
} | |
// MARK: - Properties | |
var state = State.Ready { | |
willSet { | |
willChangeValueForKey(newValue.keyPath()) | |
willChangeValueForKey(state.keyPath()) | |
} | |
didSet { | |
didChangeValueForKey(oldValue.keyPath()) | |
didChangeValueForKey(state.keyPath()) | |
} | |
} | |
// MARK: - NSOperation | |
override var ready: Bool { | |
return super.ready && state == .Ready | |
} | |
override var executing: Bool { | |
return state == .Executing | |
} | |
override var finished: Bool { | |
return state == .Finished | |
} | |
override var asynchronous: Bool { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment