我正在尝试在应用程序运行时在我的应用程序中实现备份/恢复系统。我创建了数据库的备份并将其放入 Backups 文件夹中。如果我想恢复,我删除我的持久存储,删除原始文件,复制备份并重新连接。我下面的代码有效。我的问题是,我这样做正确吗?我所做的事情是否有任何风险?感谢您对我的代码的任何反馈:
- (BOOL)resetApplicationModel {
// ----------------------
// This method removes all traces of the Core Data store and then resets the application defaults
// ----------------------
NSError *_error = nil;
NSURL *_storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Database.sqlite"];
NSPersistentStore *_store = [persistentStoreCoordinator persistentStoreForURL:_storeURL];
// Remove the SQL store and the file associated with it
if ([persistentStoreCoordinator removePersistentStore:_store error:&_error]){
[[NSFileManager defaultManager] removeItemAtPath:_storeURL.path error:&_error];
}
if (_error) {
NSLog(@"Failed to remove persistent store: %@", [_error localizedDescription]);
return NO;
}
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
[managedObjectContext release], managedObjectContext = nil;
NSString *applicationDocumentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *originalFile = [applicationDocumentDirectory stringByAppendingPathComponent:@"Database.sqlite"];
NSString *backupDatabaseFolder = [applicationDocumentDirectory stringByAppendingPathComponent:@"Backups"];
NSString *backupFile = [backupDatabaseFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"DatabaseBackup.sqlite"]];
[[NSFileManager defaultManager] copyItemAtPath:backupFile toPath:originalFile error:nil];
// Rebuild the application's managed object context
rootViewController.managedObjectContext = nil;
rootViewController.managedObjectContext = self.managedObjectContext;
return YES;
}