【问题标题】:Pre-populated Realm isn't being copied on the first launch首次启动时未复制预填充的领域
【发布时间】:2015-12-25 20:47:03
【问题描述】:

我在其他地方填充了 .realm 文件,现在我想将它用作数据库。为了让这个故事更简短,我们假设我完全按照the manual 进行了操作,除了它的最后一部分,嗯,可以治疗。

问题是当我第一次启动应用程序时,.realm 文件没有被复制,但是在我重新启动应用程序后(在模拟器中/在真实设备上),它运行良好。

我尝试引用 the migration sample,老实说,这让我更加困惑,这显然是我在这里寻求帮助的原因。

这是我错的地方:

import RealmSwift

func bundlePath(path: String) -> String? {
    let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
    return resourcePath?.stringByAppendingPathComponent(path)
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func openRealm() {
        let defaultPath = Realm.Configuration.defaultConfiguration.path!
        if let v0Path = bundlePath("names.realm") {
            do {
                try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
                try NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
                print("Copied.")
            } catch {
            print("Wasn't copied.")
            }
        }
    }
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

openRealm()

let realm = try! Realm()
print("NamesCount: \(realm.objects(Names).count)")

return true
}

感谢您抽出宝贵时间阅读本文,现在请帮帮我。为什么我会看到

没有被复制。 姓名数:0

首次发布时

复制。 姓名数:7

在第二次发射之后?

【问题讨论】:

    标签: ios xcode swift realm


    【解决方案1】:

    你在另一个地方有问题;)

    第一个 try 在第一次运行时抛出异常,因为您还没有此文件。并且copyItemAtPath 在那之后没有打电话。所以你有一个空的默认领域文件,在所有这些之后没有数据。

    func openRealm() {
        let defaultPath = Realm.Configuration.defaultConfiguration.path!
        if let v0Path = bundlePath("names.realm") {
            if NSFileManager.defaultManager().fileExistsAtPath(defaultPath) {
                do {
                    try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
                    print("Remove old file")
                } catch {
                    print("Wasn't removed")
                }
            }
            do {
                try NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
                print("Copied.")
            } catch {
                print("Wasn't copied.")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      相关资源
      最近更新 更多