3

I'm trying to add the ability to load a previously exported database into a phone app using realm. The database is contained within a zip file which I am importing into the app from an email, extracting it, and then writing the realm file to the apps local storage. After it is written to file I am loading the backup realm file, querying the objects, then writing them to the current realm.

This does work fine until I export an object that has data set in one of it's relationships. Below is the code I'm using to import the db:

let config = Realm.Configuration(path: newPath.path, readOnly: true);
let newRealm = try! Realm(configuration: config);
let realm = try! Realm();

try! realm.write {
    realm.deleteAll();
}

let firearms = newRealm.objects(Firearm);

try! realm.write {
    for firearm in firearms {
        realm.create(Firearm.self, value: firearm);
    }
}

Now every time I try calling realm.create I get a EXC_BAD_ACCESS code=2 error and am not sure what could be causing it.

Below is the firearm model:

class Firearm: Object {    
    dynamic var id = "";
    dynamic var label = "";
    dynamic var manufacturer = "";
    dynamic var model = "";
    let images = List<FirearmImage>();
    let documents = List<FirearmDocument>();
    let maintRecords = List<FirearmMaintenance>();
    let accessories = List<Accessory>();
}

Here is the firearm image model:

class FirearmImage: Object {
    dynamic var id = "";
    dynamic var fileName = "";
    dynamic var firearm: Firearm?;
}

When the db I am importing has a firearm image created, I start getting that error.

I have also tried completely replacing the realm file which does seem to work, but only after I close the app and reopen it. The goal I am aiming for is to be able to import an db file and have it reload the data that is viewable in the app without having to kill it and reopen.

Anyone know what could be causing the exception to be thrown?

DSlagle
  • 1,563
  • 12
  • 19

1 Answers1

0

I don't believe child objects are automatically copied across with their parent objects when you move them to another Realm.

As you're looping through each object, you'll most likely need to check if there are any child objects, copy them first, then the parent object second and then make sure that they're still linked up in your new copy.

Let me know if that doesn't work!

TiM
  • 15,812
  • 4
  • 51
  • 79