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?
If you already have NSFetchedResultController embed in your view controller with all delegation methods implemented (see the Duncan's answer posted earlier) then:
you subscribe your VC to context changes notification (in viewDidLoad or init)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextUpdated:)
name:NSManagedObjectContextObjectsDidChangeNotification
object:nil];
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];
}
}
be sure you unsubscribe your VC from the notifications
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With