简体   繁体   English

建立预填充领域数据库的最佳方法

[英]Best Way to Build a Pre-Filled Realm Database

My app (iOS) will have a ton of data built in (and not synced to a server). 我的应用(iOS)将内置大量数据(并且不会同步到服务器)。 I know I can take a pre-filled realm database and copy it over when the app is first used , but what I don't know is: What is the best way to build that pre-filled database? 我知道我可以获取一个预填充的领域数据库,并在首次使用该应用程序时将其复制过来 ,但是我不知道的是: 构建该预填充数据库的最佳方法什么?

Should modify my app, to statically create the realm database, by hardcoding all the objects and relations, then pull the database from the emulator: 应该修改我的应用程序,通过对所有对象和关系进行硬编码来静态创建领域数据库,然后从模拟器中提取数据库:

 let car1 = Car(color: "red")
 ...
 let car230 = Car(color: "blue")

 ...
 try realm.write{
    realm.add(car1)
    ...
    realm.add(car230)
 }

Or is there a saner approach to this? 还是有一个更明智的方法?

If the database will be always the same, I'd go for the pre-created database option due to performance. 如果数据库将始终保持不变,出于性能考虑,我会选择预先创建的数据库选项。 However, if you use database encryption, you'll have to do some runtime hacks. 但是,如果使用数据库加密,则必须进行一些运行时修改。

To achieve that check out Realm Cocoa converter project (Swift or Objective-C). 要实现这一目标,请查看Realm Cocoa转换器项目 (Swift或Objective-C)。 You can create a realm file importing from CSV, XLSX and JSON file formats. 您可以创建从CSV,XLSX和JSON文件格式导入的领域文件。

Their example is quite clear: 他们的例子很清楚:

var filePaths = [String]() // Array of file paths to each CSV file to include
let destinationRealmPath = '' // Path to the folder that will hold this Realm file

// Analyze the files and produce a Realm-compatible schema
let generator =  ImportSchemaGenerator(files: filePaths)
let schema = try! generator.generate()

// Use the schema and files to create the Realm file, and import the data
let dataImporter = CSVDataImporter(files: filePaths)
try! dataImporter.import(toPath: destinationRealmPath, schema: schema)

And you can check for more examples in their test project . 您可以在他们的测试项目中查看更多示例。

You could create a simple app (maybe a new target within the same Xcode workspace) only to pre-fill a Realm database, run it on the simulator, open the sim folder on your system and drag the Realm file from there into your main project. 您可以创建一个简单的应用程序(可能是同一Xcode工作空间中的新目标),仅用于预先填充Realm数据库,在模拟器上运行它,打开系统上的sim文件夹,然后将Realm文件从此处拖动到主项目中。 Then, when the main app launches, copy the file from your bundle to a more appropriate location (such as the documents folder) 然后,在主应用程序启动时,将文件从捆绑软件复制到更合适的位置(例如documents文件夹)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM