I've been working with Core Data and UIManagedDocument lately, and have some questions.
I've a UITableViewController in which I open a UIManagedDocument. Here I download info to the tableViewCotroller and save the info to the database and update the tableview. Now when I enter the main screen via the home button and then open the app again, I want to do work with the data from the database in the appdelegate . So in the appropriate method in appdelegate, I open the database, fetch the entities I want and change the properties in the objects I want. Now, this works, I manage to open the database and get the objects I want From the database.
My problem occours when I'm done changing data from the database in the appdelegate. Because after the appdelegate method is completed, I try to refetch data in the tableview from the same database, but at this point of time the database hasn't registered the changes made in the method called in the appdelegate. I've tried calling the saveToURL for overwriting method on the UIManagedDocument right after the changes are made inside the appdelegate and ive also tried the save: method on the managedobjectcontext. What's the right way of saving the changes so that database gets updated?
Ps: I'm writing this on an iPad, so I havnt managed to upload code, I'll upload it later.
Thanks
That is the right way - make changes in a NSManagedObjectContext then save. Remember that saveToURL is asynchronous, so what is most likely the problem is that your save has not completed by the time you perform the fetch in the table view. That's where the completion block comes in. So maybe you could have the completion block set a property in your table view which causes your fetch to happen. Something like
// appdelegate
[self.mainDatabase saveToURL:self.mainDatabase.fileURL
forSaveOperation:UIDocumentSaveForOverwriting
completionHandler:^(BOOL success) {
if (success) {
myTableView.context = self.mainDatabase.managedObjectContext;
}
}];
// TableView
- (void)setContext:(NSManagedObjectContext *)newContext {
_context = newContext;
NSArray *fetchResults = [_context executeFetchRequest:someFetchRequest error:&error];
// update model etc.
}