0

I am following the Realm documentation on migration and on bundling a realm with an app.

I am using the following code to copy the bundled Realm to be the default Realm. which works well.

let initialURL = NSBundle.mainBundle().URLForResource("bootstrap_v001", withExtension: "realm")!
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!

if Realm.Configuration.defaultConfiguration.schemaVersion == 0 {
    do {
        try NSFileManager.defaultManager().removeItemAtURL(defaultURL)
        try NSFileManager.defaultManager().copyItemAtURL(initialURL, toURL: defaultURL)
    } catch {
        // Handle error here
        print("realm delete copy error!!")
    }
}

This all works OK and I can see the correct Realm file which has data in it. However, if I use realm = try! Realm(), the results that it returns are always empty.

It should be noted that I have the following declaration at the top of AppDelegate.swift

import UIKit
import RealmSwift
let uiRealm = try! Realm()

I'm not sure if this initial global declaration of uiRealm is causing the issue. I have tried declaring local versions as well, but this doesn't seem to fix it.

It should be noted that if I re-run the application when the Realm file is already in place things are fine.

Michael Moulsdale
  • 1,488
  • 13
  • 34

1 Answers1

1

Thanks for clarifying that uiRealm instantiation at the top of your delegate. I'm pretty sure that would be what's causing the issue.

Realm caches internal copies of its Realm instances, so it's extremely important that if you're moving any files around on disk, you do so before you create any Realm() objects (Or do any Realm operations where Realm instances are created, encapsulated in an @autoreleasepool).

In this case, you should make sure that uiRealm is first touched only after you've done your initial file setup.

TiM
  • 15,812
  • 4
  • 51
  • 79