iphone - 将更新的数据库复制到 ios sdk 中的设备中

标签 iphone ios objective-c database xcode

在我的应用程序中,我使用了 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/

相关文章:

ios - 当应用程序变为事件状态时,iOS TabbarViewController隐藏选项卡栏

ios - 调用SKPaymentQueue restoreCompletedTransactions,无响应

objective-c - 尝试在 Xcode 4.5 中测试运行 iOS 4.3 的 iPad

objective-c - NSPredicate 编辑器以编程方式更改控件高度

iphone - 如何从应用程序目录中的视频中抓取单帧?

iphone - UITableView 节标题 1px 光泽/阴影重叠

iphone - 如何使用可拉伸(stretch)图像创建 UIImageView

iphone - 为什么UIWebView会缩小图片?

ios - 尝试从 didViewAppear 执行 NSLog 时出现意外行为

objective-c - 为什么遍历 NSArray 比遍历 NSSet 快?