I have a core data model with blog groups, blogs, and posts. A blog group has a to-many relationship to blogs, and each blog has a to-many relationship to posts. A post has an attribute “hasBeenRead.” Both the blog and the blog group have a attributes “numberUnreadPosts.”
I’d like to know the best practice for propagating the number of unread posts up through each relationship. For instance, if I read a post, I’d like to decrease the number of unread posts by one in both the blog and the blog group. Thanks!
There are a couple of ways to do this.
KVO observer
Your BlogGroup could watch for changes on the Blog entity
-numberUnreadPostsproperty and when it changes it can update itself.Likewise, your Blog can watch for changes on the Post entity
-hasBeenReadproperty and when it changes it can update itself which will propagate up to the BlogGroup.The problem with this design is that it assumes that the BlogGroup and Blog entities are both in memory (because you would turn the observer on in the
-awakeFromFetchmethod). This may not always be the case and I find it best not to rely on that situation.Propagate the update
When a Post changes the
-hasBeenReadproperty you can override the setter and have it call it’s parent (Blog) and tell it about the change. Blog would then update it’s own unread count and tell the BlogGroup that it has updated.This design is far more consistent and is unlikely to fail. However it can have unforeseen consequences because of the ripple. When you change a post a number of objects get fetched into memory to be updated.
Or don’t worry about it
A third option is that only the post actually has the value. You could then produce a convenience method on both the Blog and the BlogGroup that merely counts the unread from the objects below.
This is pretty simple to do but it is not an observable property so may not work in your design.
The design of your application will determine which design works better for you. If you know that the BlogGroup and Blog will always be realized when you are working with a post then option one is a better solution imho.