簡體   English   中英

領域:當試圖將具有相同主鍵值的對象添加並顯示錯誤消息時,如何捕獲異常

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM