如何在领域

时间:2018-05-22 04:25:26

标签: swift realm

我正在使用领域开发应用程序。然后我想通过应用程序上的set .realm文件初始化领域。它最初在/Users/*****/Library/Developer/CoreSimulator/Devices/~****~/Documents/default.realm/ 我希望app文件夹上的default.realm文件与storyboard和ViewController.swift以及其他文件对齐。 我怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以在Realm init方法中传递fileURL

let config = Realm.Configuration(
    // Get the URL to the bundled file
    fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
    // Open the file in read-only mode as application bundles are not writeable
    readOnly: true)

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)

有关详细信息,请参阅documentation。您还可以配置更多内容here

重要说明:请参阅上面代码中的评论:

  

以只读模式打开文件,因为应用程序包不可写

要让realm文件位于您的包中,您将无法写入它,它将是只读的。如果你想用你的应用程序发送一个预先填充的数据库,你可以在你的软件包中执行此操作,但如果你想让它可写,你需要在首次启动时将其复制到你的应用程序的文档目录,然后使用而是目录。

您在xcode中添加的资源/文件,并包含在'复制包资源中。在构建设置中包含在您的包中。捆绑包不可写。要使用您需要可写入的应用程序发送文件,需要将其移动到合适的文件夹中。通常是app文件夹。