Core Data: Fetched Results Controller causing over release/crash

941 Views Asked by At

I am using core data, and have a UITableViewController which loads the data from core data. This is a modal view and if I load the modal view for the third time, it crashes with EXC_BAD_ACCESS.

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    // Create and configure a fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Ride" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    // Create the sort descriptors array
    NSSortDescriptor *sectionTitle = [[NSSortDescriptor alloc] initWithKey:@"dateStart" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sectionTitle, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    // Create and initialize the fetch results controller
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    self.fetchedResultsController = aFetchedResultsController;
    fetchedResultsController.delegate = self;

    // Memory management
    [aFetchedResultsController release];
    [fetchRequest release];
    [sectionTitle release];
    [sortDescriptors release];

    return fetchedResultsController;

}//end

The crash says that it is coming from this line:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Ride" inManagedObjectContext:managedObjectContext];

This is in viewDidLoad:

if (managedObjectContext == nil) { 
        managedObjectContext = [MyAppDelegate instance].managedObjectContext; 
    }

Presenting the modal view:

History *history = [[[History alloc] init] autorelease];
UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:history] autorelease];
[self presentModalViewController:nav animated:YES];

Dismissing Modal:

- (void)done {
    [self dismissModalViewControllerAnimated:YES];
}

Stack Trace that gives EXC_BAD_ACCESS:

enter image description here

Now, in order to setup this view with core data, I followed the Core Data Books example project and my code looks almost identical. Why would it be crashing after a few times of loading the modal view?

1

There are 1 best solutions below

4
On BEST ANSWER

Ok, I figured it out, my managedObjectContext was not being retained because I was not using self. So, I fixed it by doing:

// Core Data
if (managedObjectContext == nil) { 
    self.managedObjectContext = [MyAppDelegate instance].managedObjectContext; 
}