How does KVO work in Operation

Hi,

I have been trying to understand how KVO is really working in the Operation.swift.

I checked out the swift-corelibs-foundation and saw this test case above (I have removed some test-related code). In the setIsReady(), the call to willChangeValue(forKey:) is marked as not implemented.

func test_CustomOperationReady() {
    class CustomOperation: Operation {

    private var _isReady = false

    override var isReady: Bool {
        return _isReady
    }

    func setIsReady() {
        willChangeValue(forKey: "isReady")
        _isReady = true
        didChangeValue(forKey: "isReady")
    }

}


let queue1 = OperationQueue()
let op1 = CustomOperation()
let op2 = BlockOperation(block: {
     // do something
})

queue1.addOperation(op1)
queue1.addOperation(op2)

op1.setIsReady()
queue1.waitUntilAllOperationsAreFinished()
}

I have 3 questions:

  1. Why does the declaration of willChangeValue(forKey:) in the extension on Operation is not giving an error that it needs to be overridden instead? This method is part of NSObject and which is the superclass of Operation here.
  2. Commenting the line willChangeValue(forKey: "isReady") in the test case will still pass the test case. Because it is executing the unimplemented method from the extension.
    Now if I create the same test case in a separate project (importing Foundation and not Swift Foundation) and comment willChangeValue(forKey: "isReady") there, the operation will never be executed. So what is the difference here? Does that mean SwiftFoundation and Foundation are different frameworks?
  3. How does KVO really works in Operation? more specifically where exactly are we observing the property changes in its implementation? There must be some code that should be observing the isReady changes and schedule the Operation once the state is changing.

Yes. swift-corelibs-foundation is a different framework. It is a new implementation in Swift of a subset of Foundation APIs for non-Apple platforms. On Apple platforms, Foundation is a proprietary (closed-source) library; you cannot see how it’s implemented.

Terms of Service

Privacy Policy

Cookie Policy