Realm:尝试添加具有相同Primary key值的Object时如何捕获异常并显示错误信息

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:

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
}

有没有更简单的方法?

您可以使用 Realm.add(_:update:)Realm.create(_:update:)update == true 来更新具有相同主键值的现有对象。或者,您可以使用 Realm.objectForPrimaryKey(_:key:) 从主键中获取现有对象。

以下是如何使用它来检查是否已经存在具有该主键的对象:

let category = Realm().objectForPrimaryKey(Category.self, key: newCategoryName)

if (category != nil) {
    //Duplicate Object with newCategoryName found
}