How to configure KVO for NSOperation via keyPathsAffectingValue?

Hi!

// MARK: Operation
public class DownloadImageOperation: Operation {
    @objc(DownloadImageOperation_State)
    enum State: Int {
        case ready, executing, finished
        func key() -> String {
            switch self {
            case .ready: return "isReady"
            case .executing: return "isExecuting"
            case .finished: return "isFinished"
            }
        }
    }
    @objc dynamic var state: State
}
// MARK: KVO
extension DownloadImageOperation: NSKeyValueObservingCustomization {
    public static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> {
        print("keyPath: \(key)") // NOTE: Never printed.
        if ([\DownloadImageOperation.isReady, \DownloadImageOperation.isExecuting, \DownloadImageOperation.isFinished].contains{ k in
            return k == key
        }) {
            return [\DownloadImageOperation.state]
        }
        return Set()
    }
    
    public static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool {
        return true
    }
}

Swift 4.2.1 (Official Xcode Toolchain 10.1)

Terms of Service

Privacy Policy

Cookie Policy