Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

realm

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

like image 794
perwyl Avatar asked Jul 13 '16 09:07

perwyl


Video Answer


1 Answers

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.

like image 183
Kyle Venn Avatar answered Oct 24 '22 23:10

Kyle Venn