不能使用带有对象映射器swift 3.0的域

时间:2017-06-06 11:34:33

标签: ios swift3 realm objectmapper

我使用Realm和Object Mapper进行JSON解析。当我创建一个同时使用Object Mapper和Realm的模型类时,我得到编译错误

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')

1 个答案:

答案 0 :(得分:2)

我使用这种模式:

我有一个BaseObject,我的所有Realm对象都继承自

open class BaseObject: Object, StaticMappable {

    public class func objectForMapping(map: Map) -> BaseMappable? {
        return self.init()
    }

    public func mapping(map: Map) {
        //for subclasses
    }
 }

然后你的班级会是这样的:

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"]
    }
}