How to make a designated initializer for NSManagedObject subclass in Swift?

后端 未结 4 1804
别那么骄傲
别那么骄傲 2020-12-25 11:10
class Alternative: NSManagedObject {

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

convenience init(text:          


        
4条回答
  •  無奈伤痛
    2020-12-25 11:56

    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
    }
    

    which would be called as

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

    In addition, you could also move the creation of the entity description into the convenience initializer instead of passing it as an argument (as motivated by Mundi's answer):

    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
    }
    

提交回复
热议问题