领域 – 添加具有初始数据项目的文件(iOS / Swift)

我正在使用 swift开发iOS应用程序,并选择了Realm作为数据库解决方案.我在AppDelegate中使用写入/添加功能从领域文档编写了默认数据,它的工作原理很好.所以在第一次启动后,我有一个* .realm文件与我的初始数据.在Realm文档中,我发现了一个名为 “Bundling a Realm with an App”的部分,我将* .realm文件添加到项目中并构建阶段.

我不明白我下一步应该做什么(关于压缩* .realm文件的一部分).我试图从Migration Example了解一个代码,但是我不知道Obj-C.

请尽可能明确的步骤,添加* .realm文件与初始数据swift ios项目,并将该数据加载到Realm数据库与第一次启动.

解决方法

在AppDelegate中实现这个函数openRealm并调用它
func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    ...
    openRealm() 

    return true
 }

func openRealm() {

    let defaultRealmPath = Realm.defaultPath
    let bundleReamPath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("default.realm")

    if !NSFileManager.defaultManager().fileExistsAtPath(defaultRealmPath) {
        NSFileManager.defaultManager().copyItemAtPath(bundleReamPath!,toPath: defaultRealmPath,error: nil)
    }
}

它会将您在应用程序中捆绑的领域文件复制到默认领域路径(如果尚不存在).之后,您通常像以前使用过的领域.

还有你在Swift讨论的迁移示例.

在Swift 3.0.1中,您可能更喜欢:

let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
    let bundleRealmPath = Bundle.main.url(forResource: "seeds",withExtension: "realm")

    if !FileManager.default.fileExists(atPath: defaultRealmPath.absoluteString) {
        do {
            try FileManager.default.copyItem(at: bundleRealmPath!,to: defaultRealmPath)
        } catch let error {
            print("error copying seeds: \(error)")
        }
    }

(但请注意可选项)

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...