Reputation: 12664
I'm using Realm with Object Mapper for JSON Parsing. When I create a model class that Use both Object Mapper and Realm than I get compilation error
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"]
}
}
if I use super.init() in init method than I get the compilation error
Case 1:
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
error:must call a designated initializer of the superclass 'QuestionSet'
Case 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')
Case 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')
Upvotes: 3
Views: 967
Reputation: 5664
I use this pattern:
I have a BaseObject
that all my Realm objects inherit from
open class BaseObject: Object, StaticMappable {
public class func objectForMapping(map: Map) -> BaseMappable? {
return self.init()
}
public func mapping(map: Map) {
//for subclasses
}
}
Then your class would look like this:
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"]
}
}
Upvotes: 2