Daniel Fernandez Y
Daniel Fernandez Y

Reputation: 188

Realm Swift - Duplicate existing nested Objects

I'm new in Realm and I trying to make a simple app. I'm currently working with this models:

class Item: Object{
    dynamic var title = ""
    dynamic var created = Date(timeIntervalSince1970: 1)
    dynamic var price = 0.0
    dynamic var image = ""
    dynamic var store: Store?
}

class Store: Object{
    dynamic var name = ""
}

When I save my new Item i do this:

@IBAction func saveItem(){
        /*some validations*/

        let item = Item()
        item.title = name
        item.price = 20.00
        item.created = Date()

        if let store = chosenStore{
            item.store = store
        }

        do{
            try realm.write {
                realm.add(item)
            }
        }catch{
            print(error.localizedDescription)
        }
    }

The problem is that I already added 5 Stores, but when I save an Item with a Store selected it creates one new Store. How can I keep the reference to a specific store without create a new one?

Upvotes: 2

Views: 717

Answers (1)

Yoam Farges
Yoam Farges

Reputation: 773

Have an unique property for your store. For example an UUID.

dynamic var uuid = UUID().uuidString

Override the primaryKey function for your Store model, and returns the previously created unique property.

override class func primaryKey() -> String? {
     return "uuid"
}

It should do the trick.

Upvotes: 1

Related Questions