Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data - update UI after object in to-many relationship change property

I have a core data model that look something like this:

Author
======
- name
- bio

- books (to-many relationship)


Book
====
- title
- release date

- author (to-one relationship)  

I present to the user a table view of authors each table cell represent an author and shows his name and the title of the latest book he wrote.

To show the list of authors I use a NSFetchedResultsController with the following NSFetchRequest :

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Author"];
request.predicate = nil;
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
request.fetchBatchSize = 20;  

My question is:

I let the user change the book title in another screen, and I want that if the user change the title of that latest book, the authors table view will update and reflect the recent change.

How can update that latest book title in my authors table view?

like image 225
Eyal Avatar asked Dec 07 '25 05:12

Eyal


1 Answers

If you already have NSFetchedResultController embed in your view controller with all delegation methods implemented (see the Duncan's answer posted earlier) then:

  1. you subscribe your VC to context changes notification (in viewDidLoad or init)

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(contextUpdated:)                          
                                                 name:NSManagedObjectContextObjectsDidChangeNotification
                                               object:nil];
    
  2. implement the contextUpdated method

    -(void)contextUpdated:(NSNotification*)notification
    {
    // if the context changed on other screens
        NSManagedObjectContext *changedContext = notification.userInfo[@"managedObjectContext"];
        if ([changedContext isEqual: self.fetchedResultsController.managedObjectContext]){
            [_tableView reloadData];
        }
    }
    
  3. be sure you unsubscribe your VC from the notifications

    -(void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
like image 114
kas-kad Avatar answered Dec 08 '25 18:12

kas-kad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!