我正在编写我的第一个iPhone/Cocoa应用程序。它在导航视图内有两个表格视图。当您触摸第一个表格视图中的一行时,您将转到第二个表格视图。我希望第二个视图显示与您在第一个视图中触摸的行相关的CoreData实体的记录。将ManagedObjectContext传递给第二个视图
我的CoreData数据在第一个表格视图中显示正常。您可以触摸一行并转到第二个表格视图。我能够将所选对象的信息从第一个视图传递到第二个视图。但我无法获得第二个视图来完成自己的CoreData抓取。对我来说,我无法让managedObjectContext对象传递给第二个视图控制器。我不想在第一个视图中执行查找并传递字典,因为我希望能够使用搜索字段来优化第二个视图中的结果,并从此处将新条目插入到CoreData数据中。
下面是从第一个视图切换到第二个视图的功能。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here -- for example, create and push another view controller.
NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
secondViewController.tName = [[selectedObject valueForKey:@"name"] description];
secondViewController.managedObjectContext = [self managedObjectContext];
[self.navigationController pushViewController:secondViewController animated:YES];
[secondViewController release];
}
这里面SecondViewController的功能崩溃:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = tName;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) { // <-- crashes here
// Handle the error...
}
}
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
// **** crashes on the next line because managedObjectContext == 0x0
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SecondEntity" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// <snip> ... more code here from Apple template, never gets executed because of the crashing
return fetchedResultsController;
}
任何的想法是什么,我做错了什么?
managedObjectContext是保留属性。
更新:我插入了NSLog([[managedObjectContext registeredObjects] description]);在viewDidLoad和它似乎managedObjectContext传递就好了。尽管如此,它仍在崩溃。
终止应用程序由于未捕获的异常“NSInternalInconsistencyException”,原因是:“+ entityForName:找不到的实体名称的NSManagedObjectModel“SecondEntity”
将初始化抓取结果控制器的代码放入viewDidLoad时会发生什么?我有一个基本上同样的东西,它适用于我,但我创建我的fetched结果控制器直接在viewDidLoad与initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName :. – Tim 2009-07-02 14:08:24
@Tim我刚刚尝试过,它以相同的方式崩溃。奇怪的是,如果我设置了一个断点,self的所有成员变量都是NULL,但标题的设置是正确的,所以不能为true。 – amo 2009-07-02 14:24:31