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

时间:2016-07-13 09:43:14

标签: swift realm

我很好奇,如果我致电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.
}

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

由于

1 个答案:

答案 0 :(得分: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)

此代码生成以下输出:

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属性已更新为新值。