perwyl
perwyl

Reputation: 323

Realm.create will it update the object with the same primary key?

I am just curious, if I call realm.create, will it auto update realm object from the realm results?

// Assuming a "Book" with a primary key of `1` already exists.
try! realm.write {
realm.create(Book.self, value: ["id": 1, "price": 9000.0], update:   true)
// the book's `title` property will remain unchanged.
}

Currently it seems like I need to read from realm again to get the latest object. Do correct me if I'm wrong.

Thanks

Upvotes: 12

Views: 10566

Answers (2)

Kyle Venn
Kyle Venn

Reputation: 8038

In case someone stumbles upon this question again, there are two ways to upsert for Realm in Swift. And to answer your question, both will result in the existing object being updated.

If you have the object, upsert with Realm.add(_:update:).

try! realm.write {
    realm.add(bookToUpsert, update: .modified)
}

If you have JSON, use Realm.create(_:value:update:)

try! realm.write {
    realm.add(Book.self, value: ["id": "1", "price": 7.99], update: .modified)
}

I pass .modified to both, but update takes an UpdatePolicy. Which can be .error, .modified, .all.

Upvotes: 1

bdash
bdash

Reputation: 18308

Yes, specifying update: true when calling Realm.create(_:value:update:) will result in the existing object being updated.

Here's a snippet based on the code you provided that demonstrates this:

class Book: Object {
    dynamic var id = ""
    dynamic var title = ""
    dynamic var price = 0.0

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


let realm = try! Realm()
let book = Book(value: ["1", "To Kill a Mockingbird", 9.99])
try! realm.write {
    realm.add(book)
}

let results = realm.allObjects(ofType: Book.self)

try! realm.write {
    realm.createObject(ofType: Book.self, populatedWith: ["id": "1", "price": 7.99], update: true)
}

print(book)
print(results)

This code produces the following output:

Book {
    id = 1;
    title = To Kill a Mockingbird;
    price = 7.99;
}
Results<Book> (
    [0] Book {
        id = 1;
        title = To Kill a Mockingbird;
        price = 7.99;
    }
)

As you can see the price property of the existing objects has updated to the new value.

Upvotes: 17

Related Questions