Search code examples
iosobjective-cuitableviewcore-datansfetchedresultscontroller

Core Data / NSFetchedResultsController - Registering changed objects related to the fetched object


I use a NSFetchedResultsController to get a list of objects which is displayed in a UITableView. If I change values in the objects the whole thing triggers and automatically reloads the changed rows. But one of the displayed values comes from related objects (one-to many relationship). Those objects have a transient title (so it's value comes again from another object). When this title changes the rows are not reloaded.

Question: Can anybody suggest a clean solution to this?

Possible Dirty Solution: I could create a transient property in the class which gets fetched with a "fake" setter method, so the NSFetchedResultsController will see a change and trigger a reload. But that's very dirty in my opinion.

Thanks in advance!


Solution

  • FRC tracks changes in properties of objects of one particular entity. Changes in objects of related entity are therefore not tracked. But you can use KVO to trigger FRC reaction.

    [Department].employees <->> [Employee].department
    

    In Employee.m:

    - (void)setTitle:(NSString *)title
    {
        [self willChangeValueForKey:@"title"];
        [self setPrimitiveValue:title forKey:@"title"];
        [self didChangeValueForKey:@"title"];
    
        [self.department willChangeValueForKey:@"employees"];
        [self.department didChangeValueForKey:@"employees"];
    }
    

    Or something like this (haven't tested it myself, though):

    - (void)didChangeValueForKey:(NSString *)key
    {
        [super didChangeValueForKey:key];
    
        if (self.department && [key isEqualToString:@"title"]) {
            [self.department willChangeValueForKey:@"employees"];
            [self.department didChangeValueForKey:@"employees"];
        }
    }