如何实现符合Mappable的NSManagedObject类

时间:2015-05-13 10:34:50

标签: ios swift nsmanagedobject initializer

我有一个直接映射实现Mappable(ObjectMapper Framework)协议的JSON的类,我尝试从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的mapping(map)AbstractModel.swift:19:9: Use of 'self' in method call 'mapping' before super.init initializes self

很遗憾,我无法在super.init(entity: NSEntityDescription, insertIntoManagedObjectContext: NSManagedObjectContext?)之前调用超级初始化程序(mapping(map)),因为我需要self来获取NSManagedObjectContext

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:6)

我不确定这个解决方案是否是解决问题的正确方法,但是我以这种方式实现了我的课程并且它有效:

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

}
}