[英]Realm: How to catch the exception when the Object with same Primary key value is tried to add and display an error message
現在,我將這種與Predicate一起使用來了解是否已經有相同的主鍵值:
類別類別:
class Category: Object
{
dynamic var name = ""
override static func primaryKey() -> String? {
return "name"
}
}
驗證是否存在具有主鍵(名稱)值的類別對象。
let predicate = NSPredicate(format: "name == %@", newCategoryName)
let realm = try Realm()
let categories = realm.objects(Category).filter(predicate).sorted("name")
if categories.count > 0
{
//Duplicate Object with newCategoryName found
}
有沒有更簡單的方法?
這是您使用它來檢查是否已經存在具有該主鍵的對象的方法:
let category = Realm().objectForPrimaryKey(Category.self, key: newCategoryName)
if (category != nil) {
//Duplicate Object with newCategoryName found
}
您可以使用帶有update == true
Realm.add(_:update:)
或Realm.create(_:update:)
來更新具有相同主鍵值的現有對象。 或者,您可以使用Realm.objectForPrimaryKey(_:key:)
從主鍵中獲取現有對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.