Patrick
Patrick

Reputation: 7195

Loading from Core data

I am saving various entities into core data. Each time I need to access this data I am reading from Core data and assigning the required entity to a mutable array.

if (managedObjectContext == nil) 
{ 
    managedObjectContext = [(iForgetAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil)
{
    // Handle the error.
    NSLog(@"mutableFetchResults == nil");
}
[self setEventsArray:mutableFetchResults];
[eventsTableView reloadData];

The problem is, I am retrieving this data from many different pages in the app.

What is the best practice when using Core Data? Should I just load the data in the App Delegate and assign the arrays there?

All advice is greatly appreciated.

Upvotes: 0

Views: 127

Answers (2)

Karl
Karl

Reputation: 1233

Using NSFetchedResultsController gives you the functionality you want. Make sure to also use the NSFetchedResultsControllerDelegate protocol. Use NSFetchRequest to do the retrieval with sorting etc.

Upvotes: 1

Mundi
Mundi

Reputation: 80271

Your setup with mutable arrays is already bad practice. Core data can sort, filter and display, arguably much better than mutable arrays.

You should consider using a NSFetchedResultsController to display your data. You can do the filtering and sorting by using predicates and sort descriptors. Such a solution should be infinitely more robust and scalable.

As for your specific question about saving, you can use the managed object context (keep a reference in your class or get it from the app delegate) to save that data anywhere.

Upvotes: 1

Related Questions