核心数据实体已创建但属性未保存

Core Data Entity Created But Attributes Not Saving

我有一个相对简单的实体。当我创建它,设置它的属性,并保存它时,它保存成功。我稍后可以检索它,它不是零,我从 MagicalRecord 收到一条成功保存的消息。

当我检索它并尝试访问任何属性时,尽管该属性为 nil。实体本身很好,但属性都是零。我在保存前检查过它们都设置正确。

我以前没有遇到过这个问题。为什么会发生?

注意:并非每次都会发生这种情况。大多数时候我调用方法来创建和保存这个实体,以后可以毫无问题地检索它。该问题是间歇性的,但可以在每个 运行.

上复制

代码:

    Entity1 *entity1 = [Entity1 MR_createEntityInContext:localContext];
    [entity1 setUpEntity:myobject];

    EntityChild *entityChild=[EntityChild MR_createEntityInContext:localContext];
    [entityChild setUpEntityChild:entity.child withContext:localContext];
    [entityChild setEntity1:entity1];

    [localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {

    }];

更新:

如果我查看 sqlite 数据库并搜索实体,它实际上根本不存在。所以 MagicalRecord 告诉我它保存了,CoreData 让我检索一个非 nil 对象(尽管具有 nil 属性)但是数据库中不存在记录。

我不明白你的代码标准。因为我是 IOS 开发的新手。我使用下面的代码进行检索。

   NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
   NSEntityDescription *entityRef = [NSEntityDescription entityForName:@"Entity1" inManagedObjectContext:appDelegate.managedObjectContext];//localContext
   [fetchRequest setEntity:entityRef];
   NSError *error=nil;
   NSArray *detailsArray = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];

   if (error) {
   NSLog(@"Unable to execute fetch request.");
   NSLog(@"%@, %@", error, error.localizedDescription);
  }

正在保存数据

NSManagedObjectContext *context = [appDelegate managedObjectContext];//localContext
NSManagedObject *objectRef = [NSEntityDescription
                                           insertNewObjectForEntityForName:@"Entity1"                                          inManagedObjectContext:context];
 [objectRef setValue:@"IOS" forKey:@"Name"];
 [objectRef setValue:@"positive" forKey:@"Attitude"];
 NSError *error;
                if (![context save:&error]) {
                    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                }

希望对您有所帮助...!

好的,我已经弄清楚了。当我保存时,代码没有问题。这实际上是另一个 class 中的某些代码从错误的上下文中检索数据的问题。当我更改上下文时它工作正常。

我仍然不确定为什么这只是偶尔发生,而不是每次代码都是 运行 但它现在可以正常工作了。

谢谢大家的帮助。