在我的应用程序中,我能够清除数据库中的所有数据.完成此操作后,将解析捆绑的
JSON,然后将其保存到数据库(以便将数据库返回到默认状态).解析和保存此JSON的操作在任何情况下都可正常工作,除非在清除并重新创建持久性存储之后,在这种情况下我得到’NSInvalidArgumentException’,原因:’无法从此NSManagedObjectContext的协调器访问对象的持久存储’.在保存在后台上下文中后尝试在我的主线程上下文中调用mergeChangesFromContextDidSaveNotification时抛出此异常.
重新创建存储是在主线程上执行的,因为解析和保存总是在后台线程上进行.这是我的托管对象上下文的getter,以确保线程安全:
- - (NSManagedObjectContext *)managedObjectContext {
- NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
- NSManagedObjectContext *threadContext = threadDictionary[ckCoreDataThreadKey];
- if (!threadContext) {
- threadContext = [self newManagedObjectContext];
- threadDictionary[ckCoreDataThreadKey] = threadContext;
- }
- return threadContext;
- }
newManagedObjectContext方法为所有新实例提供相同的NSPersistentStoreCoordinator对象.
以下是用于清除存储的代码(始终在主线程上执行):
- [self.managedObjectContext lock];
- [self.managedObjectContext reset]; //to drop pending changes
- //delete the store from the current managedObjectContext
- if ([[self.managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[self.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:error]) {
- [[NSFileManager defaultManager] removeItemAtURL:storeURL error:error];
- [[self.managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSsqliteStoreType configuration:nil URL:storeURL options:nil error:error]; //recreates the persistent store
- [self addSkipBackupAttributeToItemAtURL:storeURL];
- }
- [self.managedObjectContext unlock];