将新对象插入核心数据



我正在尝试将NSData对象插入到CoreData中,因此我不得不在事后将所有内容添加到我的应用程序中,因为我从未在选择coredata的情况下启动它。 不过没关系,因为我已经开始了一个新项目并复制了所有适当的代码以完成所有设置。

从那里我现在尝试设置 insertNewObject 方法。但是,这给了我一些问题。

我首先尝试从另一种类似的方法中传递一些 NSData

[self insertNewObject:myData];

然后我像这样使用插入新对象方法

- (void)insertNewObject:(id)sender
{
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:context];
    // If appropriate, configure the new managed object.
    // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
    [newManagedObject setValue:sender forKey:@"manufacturers"]; //not sure if this is correct, but sender has myData, and @"manufactures" is the attribute of my entity.
    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

从这里开始,当线程也得到第三行"NSManagedObject *newManagedObject..."应用程序崩溃,我收到此错误

> 2012-04-27 11:18:21.579 thecode[1452:fb03] *** Terminating app due to
> uncaught exception 'NSInternalInconsistencyException', reason:
> '+entityForName: could not locate an NSManagedObjectModel for entity
> name 'Entity''
> *** First throw call stack: (0x14b5022 0x1952cd6 0x61d47 0xa8102 0x1a595 0x199a4 0x18b99 0x15097 0x1136a49 0x1134e84 0x1135ea7
> 0x1134e3f 0x1134fc5 0x1079f5a 0x1c02a39 0x1ccf596 0x1bf9120 0x1ccf117
> 0x1bf8fbf 0x148994f 0x13ecb43 0x13ec424 0x13ebd84 0x13ebc9b 0x215b7d8
> 0x215b88a 0x733626 0x762d 0x1c75 0x1) terminate called throwing an
> exception

我已经在我的 xcdatamodeld 中设置了所需的实体和属性

任何帮助将不胜感激。

我不知道

您的 CoreData 模型,但我想您没有名称为"实体"的实体,因此当您尝试在此处插入名为"实体"的新实体时,这可能会导致崩溃:

[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:context];

当您在上面一行获取实体描述但以后从未使用它时,我猜您正在尝试插入此实体。所以你基本上要做的是:

    [NSEntityDescription insertNewObjectForEntityForName:entity.name inManagedObjectContext:context];

希望这有帮助!

还要检查您的 managedObjectContext 是否为零。当它出现时,您会收到此错误。当您实例化 fetchedResultsController 时,您将 NSManagedObjectContext 与它相关联。你从哪里得到这个背景?

如果这是在已深入到的视图控制器中,请确保将 managedObjectContext 从应用委托传递到每个后续控制器,以便它们都可以访问它。然后,您可以正确地将其传递给 fetchedResultsController。

最新更新