我正在寻找一个简单的解决方案来关闭我的数据库并重新打开它。 我的应用程序正在使用带有公式的数据库(CoreData),然后,当新公式可用时,我的应用程序将下载完整数据库并替换实际数据库。 这部分运作良好。但是,一旦下载,我想用新数据库刷新TableView。我检查了网站和互联网,但我没有找到答案。 似乎这与持久性相关但不确定。 所以我尝试重置我的上下文但是,我的TableView只在应用程序关闭并重新打开后更新。 所以,我想知道你是否有时间给我一个如何刷新甚至关闭并重新打开数据库的例子。 在此先感谢您的支持。
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"u189496386:xxxxx@xxxxx.com:21/DataBase.sqlite"]];
NSUInteger length = [fetchedData length];
ProgressDownload.progress = 0.5f;
if(length < 1)
{
ContactServer.text = @"Error downloading DataBase or Network access, please check your connection";
}
else
{
ContactServer.text = @"Server contacted, download in progress";
}
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"DataBase.sqlite"];
testEcriture = [fetchedData writeToFile:filePath atomically:YES];
if(testEcriture == YES)
{
ContactServer.text = @"Database updated";
ProgressDownload.progress = 1.0f;
}
然后,一旦回到第一个视图,执行viewDidLoad,但似乎内容没有改变。
mesProduits = [[NSMutableArray alloc] init];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Projector" inManagedObjectContext:context];
NSFetchRequest *frequest = [[NSFetchRequest alloc] init];
[frequest setEntity:entityDesc];
NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"model" ascending:YES];
[frequest setSortDescriptors:@[sortDescription]];
NSError *error;
NSArray *matchingData = [context executeFetchRequest:frequest error:&error];
答案 0 :(得分:0)
您的托管对象上下文有一个属性persistentStoreCoordinator,它提供对支持数据库的持久性存储协调器的引用。 PSC访问持久存储以读取和写入数据。
因此,要替换数据库,您可以按照以下方式执行操作:
NSManagedObjectContext *context = self.context;
NSError *error = nil;
// Save the context before doing anything else.
if (![context save:&error]) {
NSLog(@"Error saving context: %@, %@", error, [error userInfo]);
abort();
}
// Get URL to the current database...
NSPersistentStoreCoordinator *psc = context.persistentStoreCoordinator;
NSPersistentStore *currentStore = psc.persistentStores[0];
NSURL *currentURL = currentStore.URL;
// Get URL to the new database...
NSURL *appDocs = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *newDatabaseURL = [appDocs URLByAppendingPathComponent:@"DataBase.sqlite"];
// Disconnect from the current database...
if (![psc removePersistentStore:currentStore error:&error]) {
NSLog(@"Error removing store: %@, %@", error, [error userInfo]);
abort();
}
// Replace the old database with the new, keeping a backup copy...
if (![[NSFileManager defaultManager] replaceItemAtURL:currentURL withItemAtURL:newDatabaseURL backupItemName:@"DataBase.backup" options:(NSFileManagerItemReplacementUsingNewMetadataOnly | NSFileManagerItemReplacementWithoutDeletingBackupItem) resultingItemURL:nil error:&error]) {
NSLog(@"Error replacing the store: %@, %@", error, [error userInfo]);
abort();
}
// Open the new database...
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:currentURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
应该正确处理各种错误情况,我只是为了演示而记录和中止。请注意,您的新数据库必须与现有数据库的架构匹配,否则您将收到错误。显然,以前写入旧数据库的任何内容都将丢失。