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

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


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 byMundi'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}


I simply did this with a class function:

class func newInstance(text: String, notes:String,                     context: NSManagedObjectContext) -> Item {    var item = NSEntityDescription.insertNewObjectForEntityForName("Item",                inManagedObjectContext: context) as Item    item.notes = notes    item.text = text    return item}

which you can call like this (almost as pretty):

let item = Item.newInstance(text, notes:notes, context:context)


Swift 3.1 solution:

convenience init(text: String, isCorrect: Bool, image: NSData, moc: NSManagedObjectContext) {        let entity = NSEntityDescription.entity(forEntityName: "Alternative", in: moc)        self.init(entity: entity!, insertInto: moc)        // vars        self.text = text        self.isCorrect = isCorrect        self.image = image}


matomo