2016-07-13 70 views
3

我只是好奇,如果我打電話realm.create,它會自動更新realm object from the realm resultsRealm.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. 
} 

目前看來我需要再次從領域讀取以獲取最新的對象。如果我錯了,請糾正我。

感謝

回答

5

是,指定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酒店更新爲新值。

+0

感謝您的驗證和詳細的演示!事實證明,我的鑰匙有錯字! – perwyl

相關問題