在Swift中使Realm循环通用和可重用

时间:2017-12-05 20:52:10

标签: swift class generics realm

Swift 4,Xcode 9.2

以下是我的一些Realm课程:

class Dog: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Cat: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Horse: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

我们说我有一些这样的代码,我比较两个领域并创建一个具有特定Dog类的对象:

let remoteDogs = remoteRealm.objects(Dog.self)

for remoteDog in remoteDogs{
  if let localDog = realm.objects(Dog.self).filter("id = %@",remoteDog.id).first{
    // Update
    if localDog.updated < remoteDog.updated{
      //Remote is newer; replace local with it
      realm.create(Dog.self, value: remoteDog, update:true)
    }
  }
}

这很好用,但我需要在我拥有的一大堆Realm类中做同样的事情。所以我试图让它变得更通用:

let animals = [Dog.self, Cat.self, Horse.self]

for animal in animals{
  let remoteAnimals = remoteRealm.objects(animal)

  for remoteAnimal in remoteAnimals{
    if let localAnimal = realm.objects(animal).filter("id = %@",remoteAnimal.id).first{
      // Update
      if localAnimal.updated < remoteAnimal.updated{
        //Remote is newer; replace local with it
        realm.create(animal, value: remoteAnimal, update:true)
      }
    }
  }
}

这种工作,但是无论何时我想引用一个对象的属性(比如remoteAnimal.idremoteAnimal.updated),编译器就会抱怨,因为它不知道什么样的对象remoteAnimal是。{/ p>

以前有人做过这样的事吗?任何想法我怎么能这样做,以便我不必为我的每个Realm类一遍又一遍地编写相同的代码?谢谢!

1 个答案:

答案 0 :(得分:2)

Realm对象没有 ID 已更新。你可以拥有你的狗, Cat和Horse类继承自Animal类的Animal类,它具有 id 更新。由于这些属性是在Animal上定义的,因此它们可用于所有子类(Dog,Cat,Horse)。

class Animal: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Dog: Animal {
  //Other properties...
}

编辑您还可以滥用Objective C的NSObject setValue:forKey:按名称设置属性。这是非常草率的打字,而不是良好的面向对象设计,但它确实有效。这是一个游乐场:

import UIKit

class A: NSObject {
  @objc var customProperty = 0
}
let a = A()
a.setValue(5, forKey: "customProperty")
print(a.customProperty)