首页 > 解决方案 > 使用 Swift 捆绑领域文件的正确方法

问题描述

我试图将我的预填充Realm文件与我的应用程序捆绑在一起。我复制了 if 并在 Build Phase 添加了复制包资源区域。但是每次启动应用程序时,我都无法提取数据。当我查看我的应用程序在设备上创建的文件时,那里的类是空的。

这是我获取对象的方式

var allTrees: Results<trees>?
allTrees = realm.objects(trees.self)
print(allTrees?.count ?? 0) // always zero

我的AppDelegate设置

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    application.statusBarStyle = .lightContent

    let bundlePath = Bundle.main.path(forResource: "default", ofType: ".realm")
    let destPath = Realm.Configuration.defaultConfiguration.fileURL?.path
    let fileManager = FileManager.default

    if fileManager.fileExists(atPath: destPath!) {
        //File exist, do nothing
        print(destPath ?? "if loop")
    } else {
        do {
            //Copy file from bundle to Realm default path
            try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!)
        } catch {
            print(error)
        }
    }

    return true
}

我的模特班

class trees: Object {
    @objc dynamic var turkishName = ""
    @objc dynamic var latinName = ""
    @objc dynamic var seedTpye = true
    @objc dynamic var leafType = true
    @objc dynamic var botanicProperties = ""
    @objc dynamic var spreadingArea = ""
}

标签: iosswiftrealm

解决方案


推荐阅读