如何在Realm上设置.realm文件

问题描述:

我正在使用领域开发应用程序.那么我想通过应用程序上的一个.realm文件来初始化领域.它最初位于/Users/*****/Library/Developer/CoreSimulator/Devices/~****~/Documents/default.realm/ 我希望app文件夹上的default.realm文件与Storyboard和ViewController.swift等文件对齐. 我该如何解决?

I'm developing an app using realm. then I want to initialize realm by a set .realm file on the app. It is initially on /Users/*****/Library/Developer/CoreSimulator/Devices/~****~/Documents/default.realm/ I want the default.realm file on the app folder aligned with storyboard and ViewController.swift and other files. How can I solve this?

您可以在Realm初始化方法中传递fileURL

You can pass a fileURL in the Realm init method

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)

有关详细信息,请参见文档.您还可以在此处.

See the documentation for more information. There are more things you can configure here too.

重要说明:请参见上面的代码中的注释:

Important note: See the comment in the code above:

由于应用程序捆绑包不可写,因此以只读模式打开文件

Open the file in read-only mode as application bundles are not writeable

要将领域文件放在您的捆绑软件中,您将无法对其进行写操作,它将是只读的.如果您想随应用程序一起交付预填充的数据库,则可以在捆绑软件中进行,但是如果您希望其可写,则需要在首次启动时将其复制到应用程序的documents目录中,然后在其中使用该版本.该目录代替.

To have the realm file sitting in your bundle, you would not be able to write to it, it would be read only. If you want to ship a pre-filled database with your app you can do this in your bundle but if you want it to be writeable you would need to copy it to the documents directory of your app on first launch and then use the version in that directory instead.

资源/文件包含在捆绑包中.该捆绑包不可写.要在您的应用中附带一个您需要可写的文件,则需要将其移动到合适的文件夹中.通常是应用程序文档文件夹.

resources/files that you add in xcode and include in the 'copy bundle resources' in the build settings are included in your bundle. The bundle is not writeable. To ship a file with your app that you need to be writeable would need to be moved to a suitable folder. usually the app documents folder.