在运行时替换SQLite数据库

我一直在开发一个应用程序,需要在运行时替换SQLite数据库文件,我有代码来替换db但是没有更新数据库仍然显示旧数据。 请指导我。

这是用于获取文件和替换

ASIHTTPRequest *requestToDownloadDB = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.turfnutritiontool.com/dev.ios/services/turfnutritiontool_ver_two.db"]]; // ====================================================================================================== // All methods below remove old store from coordinator // ====================================================================================================== NSError *error = nil; NSPersistentStore *persistentStore = [[self.persistentStoreCoordinator persistentStores] objectAtIndex:0]; [self.persistentStoreCoordinator removePersistentStore:persistentStore error:&error]; if (error) { NSLog(@"error removing persistent store %@ %@", error, [error userInfo]); } // then update //NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; //documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"turfnutritiontool_ver_two.db"]; NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent: @"turfnutritiontool_ver_two.db"]; NSLog(@"This is store URL %@ ", storeURL); [requestToDownloadDB setDownloadDestinationPath:[NSString stringWithString:[storeURL absoluteString]]]; [requestToDownloadDB startSynchronous]; // add clean store file back by adding a new persistent store with the same store URL if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"failed to add db file, error %@, %@", error, [error userInfo]); } 

添加您的代码后,Pelase会查看我的代码。

我得到了

 NSLog(failed to add db file, error (null), (null)); 

我现在应该怎么做

你必须先删除旧商店:

 // remove old store from coordinator NSError *error = nil; NSPersistentStore *persistentStore = [[self.persistentStoreCoordinator persistentStores] objectAtIndex:0]; [self.persistentStoreCoordinator removePersistentStore:persistentStore error:&error]; if (error) { NSLog(@"error removing persistent store %@ %@", error, [error userInfo]); } // then update NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent: @"%xyz_ver_three.db"]; // add clean store file back by adding a new persistent store with the same store URL if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"failed to add db file, error %@, %@", error, [error userInfo]); } 

这应该是诀窍……

我对类似问题的解决方案就是用数据库删除文件:

 [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];