Hi,
I've noticed that when subclassing
NSOperation
, isReady
, isExecuting
and isFinished
are called twice when generating KVO notifications. This issue occurs both in Swift and Objective-C.Here is a short sample code:
let operation = CustomOperation()
operation.updateState()
@objcMembers class CustomOperation: Operation {
override var isReady: Bool { // called twice
return super.isReady
}
func updateState() {
willChangeValue(forKey: "isReady")
didChangeValue(forKey: "isReady")
}
}
In this case, the issue appears to come from the fact that
class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String>
returns ["isReady"]
for the key "ready"
and returns ["ready"]
for the key "isReady"
. Similar issue occurs for isExecuting
and isFinished
.This probably creates some loop that causes the KVO-compliant properties to be called twice.
As a workaround, if I override this property, the properties are only called once:
override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
switch(key) {
case "isReady", "isExecuting", "isFinished": return [] // can return custom state key here
case "ready", "executing", "finished": return [] // prevent calling isXXX properties twice
defaut return super.keyPathsForValuesAffectingValue(forKey: key)
}
}
- Is it a bug of NSOperation that I should report?
- Is this workaround safe to use or may it break the inner workings of NSOperation in some specific cases?
Thanks.