Realm.create会用相同的主键更新对象吗?

per*_*wyl 8 realm swift

我很好奇,如果我打电话realm.create,它会自动更新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.
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

bda*_*ash 11

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

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

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)
Run Code Online (Sandbox Code Playgroud)

此代码生成以下输出:

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;
    }
)
Run Code Online (Sandbox Code Playgroud)

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