我需要删除我的持久存储(按对象执行它不实用,因为我有超过100,000个对象).我试过这个:
- (IBAction)resetDatabase:(id)sender { NSPersistentStore* store = [[__persistentStoreCoordinator persistentStores] lastObject]; NSError *error = nil; NSURL *storeURL = store.URL; // release context and model [__managedObjectContext release]; [__managedObjectModel release]; __managedObjectModel = nil; __managedObjectContext = nil; [__persistentStoreCoordinator removePersistentStore:store error:nil]; [__persistentStoreCoordinator release]; __persistentStoreCoordinator = nil; [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error]; if (error) { NSLog(@"filemanager error %@",error); } // recreate the stack __managedObjectContext = [self managedObjectContext]; }
但是当我尝试之后将实体插入商店时,我收到此错误:
This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.
解决方法
以下是我在多个应用中执行“重置数据”功能的方法:
- (void)reset { // Release CoreData chain [_managedObjectContext release]; _managedObjectContext = nil; [_managedObjectModel release]; _managedObjectModel = nil; [_persistentStoreCoordinator release]; _persistentStoreCoordinator = nil; // Delete the sqlite file NSError *error = nil; if ([fileManager fileExistsAtPath:_storeURL.path]) [fileManager removeItemAtURL:_storeURL error:&error]; // handle error... }
基本上我只是释放CoreData链,然后删除persistentStore文件.这就是你要做的,不使用removePersistentStore,我不在乎,因为我稍后会重建persistentStore协调器.然后在下一个核心数据调用时,使用单独的惰性样式构造函数透明地重建链,例如:
- (NSManagedObjectModel *) managedObjectModel { if (!_managedObjectModel) _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; return _managedObjectModel; }