我有一个直接映射
JSON实现Mappable(ObjectMapper Framework)协议的类,我试图从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"] } }
这个实现的问题是编译器抱怨在超级初始化器之前使用self的映射(map):
AbstractModel.swift:19:9:在super.init初始化self之前,在方法调用’mapping’中使用’self’
不幸的是,我无法在映射(map)之前调用超级初始化器(super.init(实体:NSEntityDescription,insertIntoManagedObjectContext:NSManagedObjectContext?)),因为我需要self来获取NSManagedObjectContext.
我该怎么解决这个问题?
解决方法
我不确定这个解决方案是否是解决问题的正确方法,但我以这种方式实现了我的课程并且它有效:
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"] } }