Reputation: 106
Let's say I'm building an app that displays a UITableView of contacts. The user's contacts are stored on a remote server. I fetch the user's contacts from the server and store them in Core Data.
My UITableViewController loads and I fetch an array of NSManagedObject subclasses (named ContactVO) from Core Data. I use this array of ContactVOs to populate my UITableView. I then fire off a request to the server to pull the user's list of up to date contacts. When I get a response from the server, I delete all contacts from my Core Data store and then insert contacts created from the server data. At this point, I notify my UITableViewController that the data has changed and pass it the new contacts via a delegate method.
Problem: As soon as I delete the contacts from Core Data, the references to the ContactVOs that are stored in my UITableViewController are garbage.
The idea here is for the table view to always allow user interaction, yet always display the most up to date contacts available.
Things I have tried:
Create a class (Contact) with all the same properties as ContactVO and populate instances of this class with the data fetched from Core Data, then return an array of Contact objects to my UITableViewController
Create an NSDictionary for each ContactVO fetched and return an array of dictionaries to my UITableViewController
There has got to be a better way than both of these. What is the preferred method for storing results from a fetch request?
Upvotes: 0
Views: 232
Reputation: 7343
You should read about NSFetchedResultsController and it`s delegate. It helps you refreshing the data displayed in a table when the model has changed (object deleted, added, modified). You can also find a sample project in Xcode, I believe it is called Core Recipes.
Hope this helps!
Upvotes: 2