简体   繁体   中英

Pre-Populated realm database with realm file

I have contact.realm file with 10000 records in it. I want to use that preloaded realm file into my app.

Here is my code in app delegate's did finish launching :

// Inserting Contacts.Realm file to Default.Realm

let defaultPath = Realm.Configuration.defaultConfiguration.fileURL?.path
let path = Bundle.main.path(forResource: "ContactDemo", ofType: "realm")

if !FileManager.default.fileExists(atPath: defaultPath!), let bundledPath = path {
    do {
        try FileManager.default.copyItem(atPath: bundledPath, toPath: defaultPath!)
    } catch {
        print("Error copying pre-populated Realm \(error)")
    }
}

It works well for the first launch but when I delete the app and relaunch it I am getting 0 counts every time. The problem is that contents of conactDemo.realm is not getting copied into default.realm. Please help me out.

Go inside Realm class, put breakpoint into init() method and just check call trace.

在此处输入图片说明

You should replace this code:

let db = try! Realm() 

by this one:

lazy var db = try! Realm()

View controllers are instantiated from Storyboard BEFORE didFinishLaunchingWithOptions .

didFinishLaunchingWithOptions should be call before init() method of the Realm class.

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