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...
}
假设我有一些这样的代码,我比较两个 Realm 并创建一个具有特定 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.id
和 remoteAnimal.updated
),编译器都会报错,因为它不知道 remoteAnimal
是什么类型的对象。
有没有人做过这样的事情?我有什么想法可以做到这一点,这样我就不必为我的每个 Realm 类一遍又一遍地编写相同的代码了吗?谢谢!
最佳答案
Realm 对象没有id 或更新。你可以拥有你的狗, Cat 和 Horse 类继承自 Animal 类,该类是 Object 的子类并且具有 id 或 updated。由于这些属性是在 Animal 上定义的,因此它们将可用于所有子类(狗、猫、马)。
class Animal: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var updated = Date()
//Other properties...
}
class Dog: Animal {
//Other properties...
}
EDIT 你也可以滥用 Objective C 的 NSObject setValue:forKey:按名称设置属性。这是非常草率的打字,不是很好的面向对象设计,但它确实有效。这是一个 Playground :
import UIKit
class A: NSObject {
@objc var customProperty = 0
}
let a = A()
a.setValue(5, forKey: "customProperty")
print(a.customProperty)
关于swift - 在 Swift 中使 Realm Loop 通用且可重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662475/