我有一个与我的核心数据实现和线程有关的问题。它在iOS 7上运行得很好,但是我无法在iOS 6上正确地刷新主上下文。
我有两个NSPersistentStoreCoordinators指向同一个数据库文件。然后我有一个主要的上下文和一个背景上下文。所有新的子上下文都是背景上下文的子上下文。
当我在6上的后台线程中更新子上下文中的项目时,它们永远不会合并到主上下文,直到我重新启动应用程序,并且主上下文从存储中获取它们。然而,在ios7上,这一切都很好。如何确保主上下文正确地刷新合并,而不出错和重新加载db?
我知道默认情况下iOS 7打开了异步sql访问,但我在6上使用了:
NSSQLitePragmasOption : @{@"journal_mode" : @"WAL"}
以下是如何设置我的上下文:
self.mainManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[self.mainManagedObjectContext setPersistentStoreCoordinator:self.mainPersistentStoreCoordinator];
[self.mainManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[self.mainManagedObjectContext setUndoManager:nil];
self.backgroundParentContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[self.backgroundParentContext setPersistentStoreCoordinator:self.backgroundPersistentStoreCoordinator];
[self.backgroundParentContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[self.backgroundParentContext setUndoManager:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.backgroundParentContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.mainManagedObjectContext];
下面是我如何创建一个子上下文:
- (NSManagedObjectContext *)newChildManagedObjectContext
{
NSManagedObjectContext *childContext = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[childContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
[childContext setParentContext:self.backgroundParentContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextDidSave:)
name:NSManagedObjectContextDidSaveNotification object:childContext];
[childContext setUndoManager:nil];
return childContext;
}
以下是通知方法:
- (void)mainContextDidSave:(NSNotification *)notification
{
__block NSNotification *strongNotification = notification;
[self.backgroundParentContext performBlockAndWait:^{
[self.backgroundParentContext mergeChangesFromContextDidSaveNotification:strongNotification];
}];
}
- (void)backgroundContextDidSave:(NSNotification *)notification
{
[self.mainManagedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:NO];
}
- (void)managedObjectContextDidSave:(NSNotification *)notification
{
[self.backgroundParentContext performBlockAndWait:^{
NSError *error = nil;
if (![self.backgroundParentContext save:&error]) {
DNSLog(@"error saving context: %@", error);
}
}];
}
更新:
看来这在6上是行不通的。根据文档,它们在7的合并上下文方面发生了很大的变化。所以我想我必须对6采用不同的方法。
发布于 2013-10-24 10:04:19
我还没有在NSPersistentStoreCoordinators
6上使用两个iOS,但是在iOS 7中明确提到了来自不同存储协调器的上下文之间的合并更改,因此我认为在iOS 7中它已经改变了。
https://stackoverflow.com/questions/19562119
复制相似问题