我正在尝试使用核心数据来保存Google Firebase调用的数据。当我保存托管上下文时,它会保存,但当我退出应用程序并重新打开它时,所有数据都会消失。
ref.child(exhibit).observeSingleEvent(of: .value, with: { snapshot in
for item in snapshot.children {
let animalObject = animal(snapshot: item as! FIRDataSnapshot)
let managedContext = self.appDelegate!.persistentContainer.viewContext
let animalEntity = NSEntityDescription.insertNewObject(forEntityName: "Animal", into: managedContext)
animalEntity.setValue(animalObject.name, forKeyPath: "name")
animalEntity.setValue(animalObject.information!, forKeyPath: "information")
animalEntity.setValue(animalObject.imageReference!, forKeyPath: "imageURL")
self.animals!.append(animalObject)
do {
try managedContext.save()
} catch let error as NSError {
print("Couldn not save. \(error), \(error.userInfo)")
}
}
})我知道快照正确地获取了数据。此外,我还尝试了参数名为forKey而不是forKeyPath的setValue。
发布于 2017-01-02 00:20:23
关键在于“异步”这个词。您使用的是来自appDelegate的managedObjectContext,它可能在一个辅助线程的主队列上运行。您有几个选项:
Objective-C示例,假设已经设置了self.persistentContainer,并且数据在字典的NSArray中可用:`
- (void)saveData
{
NSManagedObjectContext *_privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_privateContext.persistentStoreCoordinator = _persistentContainer.persistentStoreCoordinator;
__block __typeof__(self) blockSelf = self;
[_privateContext performBlock:^(void) {
NSError *error = nil;
for (NSDictionary *animalDict in blockSelf.dataArray) {
Animal *anAnimal = [Books managedObjectWithEntity:@"Animal" managedObjectContext:_privateContext];
anAnimal.name = [animalDict valueForKey:@"name"];
anAnimal.fluffiness = [animalDict valueForKey:@"fluffiness"];
}
if ([_privateContext save:&error]) {
NSLog(@"%@ %@ Data was added and saved", [blockSelf class], NSStringFromSelector(_cmd));
} else if (error) {
NSLog(@"%@ %@ %@", [blockSelf class], NSStringFromSelector(_cmd),
error.description); //type macerror <errornumber> in Terminal for more info
} else {
NSLog(@"%@ %@ Data was added but not saved", [blockSelf class], NSStringFromSelector(_cmd));
}
}];
}https://stackoverflow.com/questions/41373255
复制相似问题