我们可以继承NSOperationQueue吗?

时间:2017-06-15 05:44:22

标签: ios objective-c

我想继承NSOperationQueue以跟踪互联网相关操作是否成功完成。是否可以继承NSOperationQueue?

1 个答案:

答案 0 :(得分:-2)

你可以很好地继承NSOperationQueue。

以下是子类分类OperationQueue

的示例
import Foundation
    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
            }
        }
    }

使用方法:  1.覆盖super.main()方法时调用main,覆盖super.start()方法时调用start。  2.操作完成或取消后,设置self.state = .finished'

有关详细信息,请参阅此link