我的核心数据对象如下:
作者(姓名)>>书(标题)>>备注(text,dateOfNote)
关系boksByAuthor>> notesOnBook
+(void)persistBooksToDisk:(NSManagedObjectContext *)workerContext
subClass:(EECoreStack*)eeCoreStack
fromURL:(NSURL*)fileURL{
[workerContext performBlock:^{
NSArray * array = [AP_TextExtract componentSeperatedByBooksFromTXTFile:fileURL];
for (NSString *body in array) {
Note *note = (Note *) [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:workerContext];
note.dateOfNote = [AP_TextExtract dateOfNoteFromString:body];
note.text = [AP_TextExtract noteTextFromString:body];
Book *book = (Book *) [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:workerContext];
book.title = [AP_TextExtract bookNameFromString:body];
[book addNotesInBook: note];
Author *author = (Author*)[NSEntityDescription insertNewObjectForEntityForName:@"Author" inManagedObjectContext:workerContext];
author.name = [AP_TextExtract authorNameFromString:body];
[author addBooksByAuthor: book];
}];
[eeCoreStack saveTemporaryWorkerContext:workerContext];
}
saveTemporaryContext:
- (void)saveTemporaryWorkerContext:(NSManagedObjectContext *)context {
[context performBlock:^{
NSError *error;
[context save:&error];
if (error) {
NSLog(@"ERROR SAVING TEMPORARY WORKER MOC %@: %@:", [error localizedDescription], [error userInfo]);
}else {
[self saveMainContext];
}
}];
}
- (void)saveMainContext {
[self.mainContext performBlock:^{
NSError *error = nil;
[self.mainContext save:&error];
if(error){
NSLog(@"ERROR SAVING MAIN MOC %@: %@:", [error localizedDescription], [error userInfo]);
}else {
[self saveMasterContext];
}
}];
}
- (void)saveMasterContext {
[self.masterContext performBlock:^{
NSError *error = nil;
[self.masterContext save:&error];
if(error){
NSLog(@"ERROR SAVING MASTER CONTEXT %@; : %@", [error localizedDescription], [error userInfo]);
}
}];
[[NSNotificationCenter defaultCenter] postNotificationName:@"doneSavingMasterContext" object:nil];
}
数据从文本文件中保存,保存遵循模式:
workerContext> mainContext> masterContext(商店)
第一次成功保存数据但稍后当它尝试保存更新的文本文件(只更改注释文本)时,会抛出以下错误:
ERROR SAVING MASTER CONTEXT保存时发生错误。
; : {
NSAffectedObjectsErrorKey = (
"<Note: 0x6000002d6570> (entity: Note; id: 0x600001424480 <x-coredata:///Note/t2371834C-1581-4A68-A56E-77E734B276CC1244> ; data:
text = \"quitely right );
NSUnderlyingException = "Cannot update object that was never inserted.";
}
有一件事我注意到,重新启动应用后,数据会被保存,但之后会再次开始提供相同的错误。
编辑1:此错误仅显示我是否更新现有属性,如果我插入新属性实例则不显示。
答案 0 :(得分:0)
更新数据时,首先使用NSFetchRequest
获取核心数据对象,然后更新必要的数据。然后尝试保存。您可能尝试在不提取的情况下更新数据。