RealmSwift +重复数据

时间:2015-12-07 08:30:29

标签: json swift realm

我对避免写入realm数据库的数据重复有一些问题。我有以下对象模型

Person.swift

class Person: Object {
    let id = RealmOptional<Int>()
    dynamic var name = ""
    let dogs = List<Dog>()

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

Dog.swift

class Dog: Object {
    dynamic var name = ""
    var owner: [Person] {
        return linkingObjects(Person.self, forProperty: "dogs")
}

Json数据

{
  "id": 1001,
  "name": "Joe",
  "dogs": ["Sally","Molly","Lucy"]
}

在将json数据解析为变量之后 - personId,personName&amp; dogNameArray,将这些数据发送到saveFunc()

func saveFunc() {

do {
    let newPerson = Person()
    newPerson.id.value = personId
    newPerson.name = personName

    let newDog = Dog()
    if dogNameArray.count > 0 {
    for dog in dogNameArray {
        newDog.name = dog
        newPerson.dog.append(newDog)
      }
    }

    let realm = try Realm()
    realm.beginWrite()
    realm.create(Person.self, value: newPerson, update: true)
    try realm.commitWrite()

} catch {
    print("create and updating error"
}

问题:数据是第一次创建的,但随后重新启动应用程序,由于primaryKey没有重新创建人员数据,这是我的意图,但狗名称保持重复。所以我的问题是,如果这个人没有被覆盖,为什么狗名仍然被添加,我做错了什么?

2 个答案:

答案 0 :(得分:1)

我们可以确保,我们检查此人是否已经存在,如果是,请不要创建和添加狗:

func saveFunc() {

  do {

    let realm = try Realm()
    if let person = realm.objectForPrimaryKey(Person.self, key: personId){
       //Nothing needs be done.

    }else {

       //Create Person and dogs and relate them.

      let newPerson = Person()
      newPerson.id.value = personId
      newPerson.name = personName

      let newDog = Dog()
      if dogNameArray.count > 0 {
        for dog in dogNameArray {
          newDog.name = dog
          newPerson.dog.append(newDog)
        }
      }

      let realm = try Realm()
      realm.beginWrite()
      realm.create(Person.self, value: newPerson, update: true)
      try realm.commitWrite()
    }


  } catch {
    print("create and updating error"
}

答案 1 :(得分:1)

另一个解决方案可能是将主键添加到链接类Dog。但是,如果这将是狗的名字,那将导致另一个Person有一个同名的狗,将共享相同的Dog实例,这取决于您的真实用例,可能仍然是适当的解决方案。