Swift Realm,以正确的方式加载预填充的数据库吗? [英] Swift Realm, load the pre-populated database the right way?

查看:56
本文介绍了Swift Realm,以正确的方式加载预填充的数据库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ios开发很陌生.

I'm pretty new to ios development.

我遵循此

I follow this migration example to use pre-populated database and change the code a little bit

这是我在AppDelegate -> func application

    let defaultPath = Realm.Configuration.defaultConfiguration.path!
    let path = NSBundle.mainBundle().pathForResource("default", ofType: "realm")

    if let bundledPath = path {

        print("use pre-populated database")
        do {
            try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
            try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath)

        } catch {
            print("remove")
            print(error)
        }
    }

我正在真实的设备中对此进行测试.

I'm testing this in a real device.

它可以工作,但是根据代码逻辑,它将始终重置为预先填充的数据库.这已得到验证:应用重新启动后,数据将重置.

It works but according to the code logic, it'll always be reset to the pre-populated database. This is verified: the data is reset after app restart.

我尝试了moveItemAtPath而不是copyItemAtPath.权限错误

I tried moveItemAtPath instead of copyItemAtPath. permission error

我试图在复制后删除预填充的数据库文件.权限错误

I tried to delete the pre-populated database file after copy. permission error

我尝试使用预先填充的数据库文件作为领域默认配置路径.错误也会发生.

I tried to use the pre-populated database file as the realm default configuration path. error occurs too.

推荐答案

是的,您的逻辑是正确的.每次执行此代码时,都会删除Documents目录中的默认Realm文件,并将其替换为应用程序捆绑包附带的静态副本.这是通过在Realm示例代码中进行设计而完成的,目的是在每次启动应用程序时演示其迁移过程.

Yeah, your logic is correct. Every time this code gets executed, the default Realm file in the Documents directory is deleted and replaced with the static copy that came with the app bundle. This is done by design in the Realm sample code in order to demonstrate the migration process each time the app is launched.

如果您只希望一次发生,那么最简单的方法是事先检查Realm文件是否已存在于默认路径中,然后仅在为"n"时执行复制. t 已经在那里. :)

If you only want that to happen one time, the easiest way to do it would be to check beforehand to see if a Realm file already exists at the default path, and then perform the copy only when it isn't already there. :)

let alreadyExists = NSFileManager.defaultManager().fileExistsAtPath(defaultPath)

if alreadyExists == false && let bundledPath = path {
    print("use pre-populated database")
    do {
        try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
        try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath)

    } catch {
        print("remove")
        print(error)
    }
}

这篇关于Swift Realm,以正确的方式加载预填充的数据库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆