0

我正在使用core data,并且有一个UITableViewControllercore data. 这是一个modal view,如果我第三次加载模态视图,它会崩溃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

崩溃说它来自这条线:

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

这是在 viewDidLoad 中:

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

呈现模态视图:

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

解雇模式:

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

给出 EXC_BAD_ACCESS 的堆栈跟踪:

在此处输入图像描述

现在,为了使用核心数据设置此视图,我遵循Core Data Books示例项目,我的代码看起来几乎相同。为什么在加载模态视图几次后会崩溃?

4

1 回答 1

0

好的,我想通了,我的 managedObjectContext 没有被保留,因为我没有使用 self. 所以,我通过这样做来修复它:

// Core Data
if (managedObjectContext == nil) { 
    self.managedObjectContext = [MyAppDelegate instance].managedObjectContext; 
}
于 2011-11-18T19:42:09.307 回答