amo*_*amo 8 iphone cocoa-touch core-data objective-c
我正在写我的第一个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];
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么想法?
managedObjectContext是保留属性.
更新:我插入了一个NSLog([[managedObjectContext registeredObjects] description]); 在viewDidLoad中,看来managedObjectContext传递得很好.但仍然崩溃.
由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'+ entityForName:无法找到实体名称'SecondEntity'的NSManagedObjectModel
Sas*_*zke 18
您可以通过首先强制转换应用程序委托来禁止在协议警告中找不到'-managedObjectContext':
if (managedObjectContext == nil) { managedObjectContext = [(MyAppDelegateName *)[[UIApplication sharedApplication] delegate] managedObjectContext]; }
Run Code Online (Sandbox Code Playgroud)
哦,这很有趣.我花了一些时间在堆栈跟踪上,我想我已经弄明白了.
所以pushViewController不是一次调用viewDidLoad,而是两次.第一次调用viewDidLoad时,对象似乎没有被正确实例化.第二次,他们是.因此,第一次运行此代码时,它无法访问managedObjectContext,并引发异常.它第二次运行,一切都很好.没有崩溃.
有很多关于viewDidLoad在Google上执行多次的问题的引用,所以我认为解决方案是不在viewDidLoad中执行此获取请求初始化.