Core Data keyPathsForValuesAffectingValueForKey only calling relationships, not attributes

谁说胖子不能爱 提交于 2019-11-30 10:15:14

It looks like a found the solution to my own problem after a couple of days and it turns out I was missing something.

After rereading the discussion of the method keysPathsForValuesAffectingValueForKey: in the NSKeyValueObserving Protocol Reference, I realized the meaning of the following sentence:

When an observer for the key is registered with an instance of the receiving class, key-value observing itself automatically observes all of the key paths for the same instance, and sends change notifications for the key to the observer when the value for any of those key paths changes.

In short, your instance should have an observer observing changes to your attribute <key>:

[myInstance addObserver:myObserver forKeyPath:attributeKey options:nil context:nil];

As soon as you have an observer registered, the protocol will call keysPathsForValuesAffectingValueForKey for your specific attribute key. If this method returns a non-empty set of key paths, KVO will emit a change notification for your attribute, if a change is made to any of these key paths, in addition to notifying you of any direct change to your attribute.

Relationship keys do get called automatically, because Core Data already uses observers to keep inverse relationships up to date.

In the particular case where you want to have an attribute depend on another attribute or relationship within the same entity, you will have to:

  1. Add an observer in the awakeFromInsert: method using addObserver:forKeyPath:options:context:
  2. Implement keyPathsForValuesAffectingValueForKey: or keyPathsForValuesAffecting<key>
  3. Implement observeValueForKeyPath:ofObject:change:context for your attribute key path to act on the relevant change notifications, i.e. updating your attribute value.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!