获取RLMException:无法设置主键属性' id'

时间:2016-07-08 20:06:48

标签: swift realm

我有一堆方法可以在Realm数据库中异步保存与视频录制相关的摄像机名称。

我的模特:

/**
 Realm object for saving the camera names used
 to record clip videos
*/
public class RMCamera: Object {

    dynamic var id = ""
    dynamic var name = ""

    override public class func primaryKey() -> String {
       return "id"
    }

}

将相机保存在Realm中的方法:

/**
 Saves camera names for offline usage after deleting
 all current entries first.

 - parameter cameraNames: An array of string with the camera names to save
 */
public func saveCameraNames(cameraNames: [String]) {

    logv(" Saving camera names...")

    concurrentQueueBg.async {

        let realm = try! Realm()

        self.deleteCamerasFromRealm(realm)

        cameraNames.forEach { camera in

            let offlineCamera = RMCamera(value: ["id": NSUUID().UUIDString, "name": camera])

            do {
                try realm.write {
                    realm.add(offlineCamera)
                }
            } catch {
                loge("Error adding offline camera")
            }
        }

    }.notify(.Main) {
        logv("✅ Camera names saved!")
    }
}

首先清除Realm中所有摄像机条目的方法:

/**
 Deletes all camera names saved in the passed Realm

 - parameter realm: A Realm database instance to use
 */
func deleteCamerasFromRealm(realm: Realm) {

    let cameras = realm.objects(RMCamera)

    try! realm.write {
        realm.delete(cameras)
    }
}

问题是每隔一段时间我就会遇到这样的错误:

Can't set primary key property 'id' to existing value '572cb087b974c25b01fa40c1'.

任何想法可能实际出错?我真的不认为我会遇到来自UUID一代的冲突。

0 个答案:

没有答案