2017-06-06 59 views
1

我使用Realm與對象映射器進行JSON解析。當我創建使用兩種對象映射器和境界比我得到一個模型類編譯錯誤無法使用對象映射器swift 3.0的領域012

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

如果我用super.init()在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')

+0

你需要一個默認的構造函數或無論你的語言(Swift)如何稱呼它。 – EpicPandaForce

+0

@EpicPandaForce如果我使用默認的init()方法,那麼我必須實現Object的其餘init方法。我不想實施。所以這裏使用方便init()使用 –

+0

嗯...然後我不確定。忽略我,斯威夫特不是我的特長:D – EpicPandaForce

回答

1

我用這個模式:

我有一個BaseObject,我所有的領域對象從

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