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:
- 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 ofNSObject
and which is the superclass of Operation here. - 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 commentwillChangeValue(forKey: "isReady")
there, the operation will never be executed. So what is the difference here? Does that mean SwiftFoundation and Foundation are different frameworks? - 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.