I am new to Core Data and got really confused about this problem. I use an NSFetchedResultsController to get my data from the Core Data storage. After trying to delete data, my app crashes and the FRC doesn't work anymore. I deleted all data and tried it again, but it still doesn't work.
The confusing thing is that a standard NSFetchRequest works.
Here is my code for the FRC:
(NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
StundenZettelAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
managedObjectContext = delegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Employer"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:@"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
//TEST to see if it works, both values are 0
int i = [[aFetchedResultsController sections] count];
int j = [[[aFetchedResultsController sections] objectAtIndex:0] numberOfObjects];
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
return fetchedResultsController;
}
Here is a code example for the NSFetchRequest which works. (I used the code from the apple tutorial):
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employer" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
Does anyone have any idea why this does not work?