Force NSFetchedResultsController update when association count changes

谁都会走 提交于 2019-12-12 11:35:29

问题


I have an NSFetchedResultsController which displays a list of items in a table view, including a count of an associated entity. When an object is added for this association (using addXXXObject), no callbacks are called to notify my controller of the update.

How can I receive a notification of an object being added to the parent entity's NSSet, or otherwise force the fetched results controller to update?

To be clear, I'm currently retrieving the count using parent.children.count, which may be suboptimal. Is there a better way to go about this whole thing? It's basically just a screen like the iPhone Mail app, with folders showing a count of messages inside.


回答1:


My model is a little different, but it can easily be translated to your one.
I got a tree-like structure:

  • Element
    • title
    • parent (to-one)
  • Folder : Element
    • children (to-many)
  • File : Element

When a file gets added or deleted, only the first folder in the queue up gets notified about this change. When a file's title changes, not a single folder would get notified. So, what to do?
I tried overriding -willChangeValueForKey: and -didChangeValueForKey: in my Element class.

- (void)willChangeValueForKey:(NSString *)key
{
    [super willChangeValueForKey:key];
    [self.parent willChangeValueForKey:@"children"];
}

- (void)didChangeValueForKey:(NSString *)key
{
    [super didChangeValueForKey:key];
    [self.parent didChangeValueForKey:@"children"];
}

Basically, what this does is forcing the parent folder to update because one of its children changed.
Hope it works for you, too.



来源:https://stackoverflow.com/questions/3859421/force-nsfetchedresultscontroller-update-when-association-count-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!