Henny Lee
Henny Lee

Reputation: 3052

Delete relationship and object from context in NSManagedObject deinit

I have a NSManagedObject with a to many relationship looking like this:

class Foo: NSManagedObject {

    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).model.context

    @NSManaged var something: NSSet

    // Some setup etc.
}

When I'm deleting this object from the context, I'd like to delete something as well and tried doing so using deinit in the class Foo:

deinit {
    print(something.count) // prints 0

    something.forEach { context.deleteObject($0) }
}

When I delete an instance of Foo, deinit will be called but somehow the relation with something is lost before deinit is called. Is there a way to delete something using deinit instead of deleting it separately and manually?

Upvotes: 1

Views: 120

Answers (1)

Wain
Wain

Reputation: 119031

This is what the cascade delete rule on the relationship is for. Set it in the model view in Xcode.

Upvotes: 1

Related Questions