简体   繁体   中英

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). 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). You can create a realm file importing from CSV, XLSX and JSON file formats.

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. Then, when the main app launches, copy the file from your bundle to a more appropriate location (such as the documents folder)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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