What is the best practice to reference model objects in views with Core Data?
I have an NSManagedObject that described an animal, it has the attributes "name", "species", "scientificName" etc. I display all animals in a UITableView and managed the NSManagedObjects with an NSFetchedResultsController.
To provide my table view cells with the information necessary to render the content so far I just weakly referenced them to my NSManagedObject describing the animal. However, sometimes the NSManagedObject should get faulted and when the table view cells are redrawn, they re access the properties of the object and thus prevent the fault.
What are the best practices to provide view objects with information when using core data as data source? If possible I would like to avoid copying all attributes of the NSMa开发者_开发问答nagedObject over to the table view cell.
I believe it is a good practice to clearly separate the Model, View and Controller layers. Especially making sure the Views are not holding Model state. Holding on to a NSManagedObject
holding on to a Model object. Copying some data is unavoidable.
I usually implement a method for "painting" the View with the Model data. Something like this in the UITableViewCell
subclass:
-(void)configureWithAnimal:(NSManagedObject*)animal {
self.nameLabel.text = [animal valueForKey:@"name"];
self.speciesLabel.text = [animal valueForKey:@"species"];
// Etc.
}
This way it is a single line of code in the UITableViewController
subclass to setup the cell, independently of newly created or reused cells. And if many tables wants to reuse the custom cell then not all f them need to reimplement the code to seeing up the cell.
精彩评论