insertNewObject into coreData

时间:2012-04-26 23:34:15

标签: iphone ios core-data

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

从那里开始我正在尝试设置insertNewObject方法。然而,这给了我一些问题。

我首先尝试从其他方法(例如

)传递一些NSData
[self insertNewObject:myData];

然后我就像这样使用insertNewObject方法

- (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

中设置了所需的实体和属性

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我不知道您的CoreData模型,但我猜您没有名称为“Entity”的实体,因此当您尝试在此处插入名为“Entity”的新实体时,这可能会导致崩溃:< / p>

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

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

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

希望这有帮助!

答案 1 :(得分:1)

同时检查您的managedObjectContext是否为nil。你会得到这个错误。实例化fetchedResultsController时,您将NSManagedObjectContext与它关联。你从哪里得到了这个背景?

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

相关问题