当核心数据中的子关系实体发生更改时通知父实体
当其关系对象发生更改时,是否可以在父实体中接收回调或通知?当实体的属性发生变化时,这非常有用。以下方法...
- (void)didChangeValueForKey:(NSString *)key
在我的 Entity 子类上调用。但是,当其中一个关系中的属性发生更改时,不会调用此方法。
我想要做的是,当父实体的任何一个属性或关系对象发生更改时,更新父实体上的时间戳属性。
Is it possible to receive a callback or notification in the parent Entity when any one it's relationship objects changes? This works great when an attribute of the Entity changes. The following method...
- (void)didChangeValueForKey:(NSString *)key
is invoked on my Entity subclass. However this method is not invoked when an attribute in one of the relationships changes.
What I'm trying to do is update the timeStamp attribute on my parent Entity when any one of its attributes or relationship objects changes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
父实体可以将自己设置为关系的观察者,并且当该关系发生变化时它将收到通知。但是,只有在实际关系(添加或删除子项)发生时才会触发。
监视特定的子实体要困难得多。有几种方法可以解决这个问题:
可能还有其他解决方案,但在这三个解决方案中我推荐#2。它的设置非常简单,并且对性能的影响非常小。
The parent entity can set itself as an observer of the relationship and it will get notified when that relationship changes. However that will only be fired when the actual relationship (adding or removing a child) occurs.
To watch for a specific child entity is far more tricky. There are a couple of ways to go about it:
NSManagedObjectContextDidSaveNotification
and look to see if any of its children are in that saveThere may be other solutions but of the three I recommend #2. It is pretty easy to set up and the performance impact is pretty minimal.
在另一个答案中,我发现 1,2 和 3 效率太低。特别是 2 以及“Parent Watching it's Child”博客文章中的示例。我的问题是,每个父对象都必须响应上下文通知,并且基本上每个对象都被保存(如果它是子对象)(不用介意 ContextDidSave 在这种情况下更合适!)。相反,我会提出选项 4:
我的解决方案更加高效,并且对我来说更加面向对象,因为正在更改的对象正在响应其自身的更改。要实现这一点,在子对象中使用:
要更新父时间戳,可以使用以下简洁的解决方案(倒数第二篇文章)我一直在使用可能会有所帮助,例如在父级使用中:
In the other answer I found 1,2 and 3 too inefficient. Particularly 2 and the example in the "Parent Watching it's Child" blog post. My issue with that is every single parent had to respond to the context notification and essentially every object being saved if it is the child (never mind the fact ContextDidSave is more appropriate in that case!). Instead, I would propose an option 4:
My solution is more efficient and feels more object-oriented to me since the object that is changing is responding to its own change. To implement this, within the child object use:
To update the parent timestamp, the following neat solution (second last post) I've been using might help, e.g. in the parent use: