...我想更新記錄,但它獲取和設置值後,似乎並沒有真正保存更新記錄。核心數據後臺線程不能更新記錄
isUpdate
是一個布爾我有安裝程序告訴我,我是否正在運行第一次解析/保存或者它是否是我需要更新的記錄。在我的情況下,當我更新記錄時,它實際上並未在我的商店中更新。
我使用MagicalRecord幫手。這裏是我的代碼:
// Create background context
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] init];
[backgroundContext setPersistentStoreCoordinator:[NSPersistentStoreCoordinator defaultStoreCoordinator]];
// Save the background context and handle the save notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:backgroundContext];
// Parsing data...
//..
Record *record;
if (!isUpdate) {
record = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:backgroundContext];
} else {
NSPredicate *recordPredicate = [NSPredicate predicateWithFormat:@"SELF.tag == %@", [[node attributeForName:@"tag"] stringValue]];
record = [Record findFirstWithPredicate:recordPredicate];
}
[record setTitle:[[recordNode attributeForName:@"title"] stringValue]];
// Parsing other data...
//..
NSError *error = nil;
// save the context
[backgroundContext save:&error];
if (error) {
NSLog(@"An error occurred: %@", error);
}
而這裏的通知:
- (void)backgroundContextDidSave:(NSNotification *)notification {
// Make sure we're on the main thread when updating the main context
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(backgroundContextDidSave:)
withObject:notification
waitUntilDone:NO];
return;
}
// merge in the changes to the main context on the main thread
[[NSManagedObjectContext defaultContext] mergeChangesFromContextDidSaveNotification:notification];
}
您是否設置了斷點,首先在isUpdate的if/else檢查中查看哪個被調用;然後在通知處理程序中?你有沒有檢查mergeChangesFromContext ...被調用,或者它不是? –
是的,兩者都被正確調用。 – runmad