Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
领域iOS问题_Ios_Swift_Swift3_Realm - Fatal编程技术网

领域iOS问题

领域iOS问题,ios,swift,swift3,realm,Ios,Swift,Swift3,Realm,我想在我的应用程序中加载预填充的领域数据库。所以我要做的是: let bundlePath = Bundle.main.path(forResource: "default", ofType: "realm") let destPath = Realm.Configuration.defaultConfiguration.fileURL?.path let fileManager = FileManager.default if fileManager.fileExists(atPath: d

我想在我的应用程序中加载预填充的领域数据库。所以我要做的是:

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("File exists")
} else {
    do {
        //Copy file from bundle to Realm default path
        try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!)
        print("Copied")
    } catch {
        print("\n",error)
    }
}
这部分总是返回true,我得到
文件存在
即使我重置了模拟器内容和设置。 第二:当我几乎不复制我的领域数据库文件而不检查文件是否存在时,这段代码

let realm = try! Realm()
var posts: Results<Post> {
    get {
        return realm.objects(Post.self)
    }
}
let realm=试试看!领域()
var员额:结果{
得到{
返回realm.objects(Post.self)
}
}

第一次运行时返回空帖子。当我第二次运行应用程序时,我得到了预填充的db。我错了什么?

在运行代码之前,您是否试图访问域?如果是,那么它可能会自动创建一个空的.realm文件,但是您的
fileExistsAtPath
方法将返回true。您是否有代码
let realm=try!Realm()
是否作为视图控制器中的实例变量?视图控制器是在
didfishlaunchwithoptions
之前从情节提要实例化的。请确保并将其修改为
lazy var realm=try!Realm()
,然后从模拟器中删除该应用程序,然后重试。@kishikawakatsumi非常感谢您。所有问题都在
中!