Henny Lee Henny Lee - 1 month ago 23
Swift Question

Failing NSManagedObject still being saved

In my custom NSManagedObject I'm using a failable initializer. But even when it fails and I save the NSManagedObjectContext, the object is being saved into Core Data.

NSManagedObject:

class Foo: NSManagedObject {

@NSManaged var a: String
@NSManaged var b: String

convenience init?(context: NSManagedObjectContext, a: String?, b: String?) {
let description = NSEntityDescription.entity(forEntityName: "Foo", in: context)!
self.init(entity: description, insertInto: context)

if let a = a { self.a = a } else { return nil }
if let b = b { self.b = b } else { return nil }
}
}


How can I fail this initializer and still saving the context without having the failed object to be saved?

Answer

You need to fail sooner.

convenience init?(context: NSManagedObjectContext, a: String?, b: String?) {
    if a == nil {return nil}
    if b == nil {return nil}
    // ...
}

This is legal because in modern Swift it is permitted to fail before fulfilling the "contract" of an initializer.