我正在将一个项目迁移到 Swift 3 并且遇到了 RealmSwift (2.6.1) 和 Genome (3.2.0) 的一些问题。我在 Xcode 中收到 Realm 的错误,说我需要这些初始化:
required convenience init(realm: RLMRealm, schema: RLMObjectSchema) {
self.init(realm: realm, schema: schema)
}
required convenience init(value: Any, schema: RLMSchema) {
self.init(value: value, schema: schema)
}
但是,除了 RealmSwift 之外,这还需要导入 Realm,并且当我的类被初始化时,它会尝试使用 RLMRealm 而不是 Realm。警告说'必需'初始化程序'init(realm:schema :)'必须由'Object'的子类提供,但所需的init使用RLMRealm而不是Realm 有什么建议吗?
我也在使用需要这个初始化的基因组,这就是为什么 Realm 首先要求初始化:
required convenience init(node: Node, in context: Context) throws {
self.init()
}
所以 inits 看起来像这样:
class BaseModel : RealmSwift.Object, MappableBase, Identifiable {
required init() {
super.init()
}
required convenience init(node: Node, in context: Context) throws {
self.init()
}
required convenience init(realm: RLMRealm, schema: RLMObjectSchema) {
self.init(realm: realm, schema: schema)
}
required convenience init(value: Any, schema: RLMSchema) {
self.init(value: value, schema: schema)
}
在没有任何这些初始化程序的情况下,在 Swift 2.3 中一切正常(使用相应的 Swift 2.3 版本的 Realm 和 Genome),但现在它无法正常工作。
整个模型:
import RealmSwift
import Genome
import Realm
protocol Identifiable {
var identifier: String { get set }
}
class BaseModel : RealmSwift.Object, MappableBase, Identifiable {
required init() {
super.init()
}
required convenience init(node: Node, in context: Context) throws {
try self.init(node: node, in: context)
}
required convenience init(realm: RLMRealm, schema: RLMObjectSchema) {
self.init(realm: realm, schema: schema)
}
required convenience init(value: Any, schema: RLMSchema) {
self.init(value: value, schema: schema)
}
dynamic var identifier = ""
dynamic var updatedAt: Date?
override static func primaryKey() -> String {
return "identifier"
}
static func newInstance(_ node: Node, context: Context = EmptyNode) throws -> Self {
let map = Map(node: node, in: context)
let new = self.init()
try new.sequence(map)
return new
}
func sequence(_ map: Map) throws {
switch map.type {
case .fromNode:
if self.identifier.isEmpty {
// only map id if there isn't one, otherwise Realm complains about modified primaryKey
try self.identifier <~ map["id"]
}
updatedAt = Date()
case .toNode:
if !self.identifier.isEmpty {
try self.identifier ~> map["id"]
}
}
}
func objectRepresentation() -> [String : AnyObject] {
if let result = try? self.toObject() {
return result as? [String : AnyObject] ?? [:]
} else {
return [:]
}
}
static func objectInRealm(_ realm: Realm, identifier: String?) -> Self? {
if let identifier = identifier {
return realm.object(ofType: self, forPrimaryKey: identifier)
} else {
return nil
}
}
static func createOrFindObject(inRealm realm: Realm, identifier: String) -> Self {
if let foundObject = realm.object(ofType: self, forPrimaryKey: identifier) {
return foundObject
} else {
return realm.create(self, value: ["identifier" : identifier], update: false)
}
}
}