【发布时间】:2010-11-07 15:42:37
【问题描述】:
我正在编写我的第一个 iPhone/Cocoa 应用程序。它在导航视图中有两个表视图。当您在第一个表格视图中触摸一行时,您将被带到第二个表格视图。我希望第二个视图显示 CoreData 实体中与您在第一个视图中触摸的行相关的记录。
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:找不到实体名称“SecondEntity”的 NSManagedObjectModel”
【问题讨论】:
-
将初始化获取结果控制器的代码放入 viewDidLoad 会发生什么?我有一个应用程序基本上做同样的事情,它对我来说很好,但我直接在 viewDidLoad 中使用 initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName: 创建我的获取结果控制器。
-
@Tim 我刚试过,它以同样的方式崩溃。奇怪的是,如果我设置一个断点,self的所有成员变量都是NULL,但标题确实设置正确,所以这不可能是真的。
标签: iphone objective-c cocoa-touch core-data