在我的应用程序中,我使用了 sqlite 数据库。我将应用程序的 1.0 版本提交到应用程序商店。但在那之后我对数据库做了一些更改,比如插入一些新行。
然后提交了1.1版本的app。 但我将无法获得更新的数据库,因为旧的数据库已经存在于设备中。
我该如何解决这个问题?
如果我删除应用程序然后安装新版本的应用程序,那么我得到了更新的数据库。
//My code for copy of DB is as follow:
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"xxx.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"xxx.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
我在 appDidFinishLaunching 方法中调用了这个方法。
当新版本可用时,如何在不删除应用程序的情况下获取更新的数据库
最佳答案
您可以使用 NSUserDefaults为此。
在您的新版本中添加此代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"1.1"]])
{
[self removeDatabase];
[self createEditableCopyOfDatabaseIfNeeded];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"1.1"];
}
//Other stuffs
}
删除旧数据库文件的方法:
- (void)removeDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *removeDBPath = [documentsDirectory stringByAppendingPathComponent:@"xxx.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if(success)
{
[fileManager removeItemAtPath:writableDBPath error:&error]
}
}
关于iphone - 将更新的数据库复制到 ios sdk 中的设备中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16333906/