[英]iPhone Core Data - How to remove NSManagedObject from context?
[英]error with core data with nsmanagedobject context
由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“ + entityForName:找不到实体名称“人”的NSManagedObjectModel” *
该实体在数据模型文件中创建,我将核心数据功能添加到了应用程序委托文件中。
我正在尝试通过以下方法在选项卡中的第一个视图控制器中使用核心数据:
- (IBAction)save:(id)sender {
NSLog(@"String is %d", [choiceSeg selectedSegmentIndex]);
NSManagedObjectContext *context = self.managedObjectContext;
Persons *person = (Persons *)[NSEntityDescription insertNewObjectForEntityForName:@"Persons" inManagedObjectContext:context];
NSNumber *ageValue = [NSNumber numberWithInt:[choiceSeg selectedSegmentIndex]];
[person setAge:ageValue];
// Save the context
if (![context save:nil]) {
// error checking
}
另外,我确实在视图中合成了managedObjectContext。
我做错了什么?
当您的NSManagedObjectContext
实例为nil时,会发生此错误。 向视图控制器提供上下文的推荐方法是通过引用传递。 将上下文从您的应用程序委托通过UITabBarController
传递到第一个视图控制器非常简单。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
{
// Assuming you don't already have a property for this (i.e. setup by a storyboard)
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
if (!tabBarController.viewControllers.count)
return;
FirstViewController *fvc = (FirstViewController *)[tabBarController.viewControllers objectAtIndex:0];
// Assumes that this view controller has a public writable @property for a context.
fvc.managedObjectContext = self.managedObjectContext;
// ... [self.window makeKeyAndVisible]; etc...
}
我意识到这不是最好的方法,因为可以重新排列标签栏项目,并且我们正在明确寻找第一个项目。 在尝试在其上设置上下文之前,请先检查返回的视图控制器的类。
好的,所以我将AppDelegate.h导入到我的视图控制器中,并使用其ManagedObjectContext在核心数据中输入一个项目。
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
有用!
但是我想知道是否每次需要使用核心数据时都必须导入委托并获取对上下文的本地引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.