我有一个相对简单的实体。当我创建它,设置它的属性,并保存它时,它保存成功。我稍后可以检索它,它不是零,我从 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]);
}
希望对您有所帮助...!
关于ios - 核心数据实体已创建但属性未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630057/