I have a class that maps directly JSON implementing the Mappable
(ObjectMapper Framework) protocol and I'm trying to inherit from NSManagedObject
.
class AbstractModel: NSManagedObject, Mappable {
@NSManaged var uuid: String?
@NSManaged var updatedAt: String?
@NSManaged var createdAt: String?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
uuid <- map["uuid"]
updatedAt <- map["updatedAt"]
createdAt <- map["createdAt"]
}
}
The problem with this implementation is that the compiler complains about the mapping(map)
that uses self before the super initializer:
AbstractModel.swift:19:9: Use of 'self' in method call 'mapping' before super.init initializes self
Unfortunately I cannot call the super initializer (super.init(entity: NSEntityDescription, insertIntoManagedObjectContext: NSManagedObjectContext?)
) before mapping(map)
because I need self
to get the NSManagedObjectContext
.
How am I supposed to solve this problem?
I'm not sure if this solution is the proper way to solve the problem but I implemented my class that way and it worked:
class AbstractModel: NSManagedObject, Mappable {
@NSManaged var uuid: String?
@NSManaged var updatedAt: String?
@NSManaged var createdAt: String?
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: DBUtils().getManagedObjectContext())
}
required init?(_ map: Map) {
var ctx = NSManagedObjectContext.MR_defaultContext()
var entity = NSEntityDescription.entityForName("AbstractModel", inManagedObjectContext: ctx)
super.init(entity: entity!, insertIntoManagedObjectContext: ctx)
mapping(map)
}
func mapping(map: Map) {
uuid <- map["uuid"]
updatedAt <- map["updatedAt"]
createdAt <- map["createdAt"]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With