0

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?

Jeremy Z
  • 106
  • 2
  • 8
  • Probably I am not understanding well your problem, but this sounds normal, as soon as the datasource has changed, you have to call [yourTable reloadData], and then you have all refreshed. Also, you could use an array of NSManagedObject , without the need of having a similar class. Or just go, as other suggested, with NSFetchedResultsController, in this case just remember to set delegate = nil when mass update, then delegate=self when finished. – Leonardo Dec 18 '12 at 11:04

1 Answers1

2

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!

Levi
  • 7,313
  • 2
  • 32
  • 44
  • This does seem like a solid solution. Unfortunately, my current view controller is a lot more complex than the scenario described above. In the instance where your tableview's data is based on one fetch request, NSFetchedResultsController looks to be a useful class. I'm marking this answer correct, because I believe it is a correct answer to my posted question. I would love to hear more suggestions though. – Jeremy Z Dec 21 '12 at 23:21