swift – Realm.create会用同一个主键更新对象吗?

swift – Realm.create会用同一个主键更新对象吗?,第1张

概述我只是好奇,如果我调用realm.create,它会从领域结果自动更新领域对象吗? // 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)/ 我只是好奇,如果我调用realm.create,它会从领域结果自动更新领域对象吗?
// 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.}

目前看起来我需要再次从领域读取以获取最新的对象.如果我错了,请纠正我.

谢谢

是的,在调用Realm.create(_:value:update :)时指定update:true将导致更新现有对象.

这是基于您提供的代码的片段,演示了这一点:

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)

此代码生成以下输出:

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;    })

如您所见,现有对象的price属性已更新为新值.

总结

以上是内存溢出为你收集整理的swift – Realm.create会用同一个主键更新对象吗?全部内容,希望文章能够帮你解决swift – Realm.create会用同一个主键更新对象吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1089715.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存