简体   繁体   中英

KVO method firing twice on NSManagedObject property

As the title says, I'm observing an NSManagedObject property with KVO. The method override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) is firing twice : The first time when assigning a new value to the property, and the second time when I'm saving the context in CD. I'm doing that immediately after setting the property value. I'm having another problems in the code because of that, my question is why is this happening, and what would be the right way to do it (set the property, saving the context and firing the method once). Maybe I shouldn't save the context immediately after?

I believe my above comment (intuition) is actually correct. It seems to be undocumented, but observed on all platforms that mergeChangesFromContextDidSaveNotification (ie when your MOC saves) triggers a refresh on all properties. cf: KVO notifications after mergeChangesFromContextDidSaveNotification

a suggestion for how to handle the behavior: kvo code, in general, should be idempotent and fast, precisely because it could get called often, ie when the keypath is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM