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

时间:2018-02-07 21:15:33

标签: ios swift realm

我的应用程序(iOS)将内置大量数据(并且不会同步到服务器)。我知道我可以take a pre-filled realm database and copy it over when the app is first used,但我不知道的是:构建预填充数据库的最佳方法是什么?

应修改我的应用程序,通过硬编码所有对象和关系来静态创建领域数据库,然后从模拟器中提取数据库:

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

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

或者对此有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

如果数据库总是相同的,我会因为性能而选择预先创建的数据库选项。但是,如果使用数据库加密,则必须执行一些运行时操作。

实现检查Realm Cocoa converter project(Swift或Objective-C)。您可以创建从CSV,XLSX和JSON文件格式导入的领域文件。

他们的例子很清楚:

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)

您可以在test project中查看更多示例。

答案 1 :(得分:1)

您可以创建一个简单的应用程序(可能是同一个Xcode工作区中的新目标),只是为了预先填充Realm数据库,在模拟器上运行它,打开系统上的sim文件夹并从那里拖动Realm文件你的主要项目。 然后,当主应用程序启动时,将文件从捆绑包复制到更合适的位置(例如文档文件夹)