我正在使用Realm和Object Mapper进行JSON解析。当我创建同时使用对象映射器和领域的模型类时,出现编译错误error:must call a designated initializer of the superclass 'QuestionSet'
import ObjectMapper
import RealmSwift
class QuestionSet: Object, Mappable {
//MARK:- Properties
dynamic var id:Int = 0
dynamic var title:String?
dynamic var shortTitle:String?
dynamic var desc:String?
dynamic var isOriginalExam:Bool = false
dynamic var isMCQ:Bool = false
dynamic var url:String?
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
//mapping the json keys with properties
public func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
shortTitle <- map["short_title"]
desc <- map["description"]
isMCQ <- map["mc"]
url <- map["url"]
isOriginalExam <- map["original_pruefung"]
}
}
如果我在init方法中使用super.init()比得到编译错误
情况1:
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
error:must call a designated initializer of the superclass 'QuestionSet'
情况2:
//Impl. of Mappable protocol
required convenience init?(map: Map) {
super.init()
}
Convenience initializer for 'QuestionSet' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')
情况3:
//Impl. of Mappable protocol
required convenience init?(map: Map) {
super.init()
self.init()
}
error 1: must call a designated initializer of the superclass 'QuestionSet'
Initializer cannot both delegate ('self.init') and chain to a superclass initializer ('super.init')
Convenience initializer for 'QuestionSet' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')
最佳答案
我使用这种模式:
我有一个BaseObject
,我所有的Realm对象都从那里继承
open class BaseObject: Object, StaticMappable {
public class func objectForMapping(map: Map) -> BaseMappable? {
return self.init()
}
public func mapping(map: Map) {
//for subclasses
}
}
然后您的 class 如下所示:
import ObjectMapper
import RealmSwift
class QuestionSet: BaseObject {
//MARK:- Properties
dynamic var id:Int = 0
dynamic var title:String?
dynamic var shortTitle:String?
dynamic var desc:String?
dynamic var isOriginalExam:Bool = false
dynamic var isMCQ:Bool = false
dynamic var url:String?
//mapping the json keys with properties
public func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
shortTitle <- map["short_title"]
desc <- map["description"]
isMCQ <- map["mc"]
url <- map["url"]
isOriginalExam <- map["original_pruefung"]
}
}