如何在Swift中为NSManagedObject子类创建指定的初始化程序?
收藏

class Alternative: NSManagedObject {

    @NSManaged var text: String
    @NSManaged var isCorrect: Bool
    @NSManaged var image: NSData
} 

convenience init(text: String, isCorrect: Bool, entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
        let alternative = Alternative(entity: entity, insertIntoManagedObjectContext: context) as Alternative
        alternative.text = text
        alternative.isCorrect = isCorrect
        return alternative
}

我想制作一个方法,让我通过此调用初始化新对象:

let newAlternative = Alternative("third platform", True, entityDescription, managedObjectContext)

但是我得到了错误:

Convenience initializer for Alternative must delegate with self.init

为了使示例用法正常工作,我需要在初始化程序中进行哪些更改?

最佳答案

A convenience initializer must call the designated initializer on self:

convenience init(text: String, isCorrect: Bool, entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
    self.init(entity: entity, insertIntoManagedObjectContext: context)
    self.text = text
    self.isCorrect = isCorrect
}

这将被称为

let newAlternative = Alternative(text: "third platform", isCorrect: true,
     entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext)

此外,您还可以将实体描述的创建移至便捷初始化器中,而不是将其作为参数传递(由 蒙迪的答案):

convenience init(text: String, isCorrect: Bool, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
    let entity = NSEntityDescription.entityForName("Alternative", inManagedObjectContext: context)!
    self.init(entity: entity, insertIntoManagedObjectContext: context)
    self.text = text
    self.isCorrect = isCorrect
}

    公众号
    关注公众号订阅更多技术干货!