nambatee
nambatee

Reputation: 1568

Core Data delete object on reassignment

In Core Data, is it possible for have objects automatically deleted on reassignment?

For example if I have

class Person: NSManagedObject {
  @NSManaged public var name: String?
  @NSManaged public var group: Group?
}

class Group: NSManagedObject {
  @NSManaged public var people: Set<Person>?
}

and assign a new set to a group's people property:

group.people = [some new set of <Person>]`

and then save the current context. I would like all the previous Person objects in the previous set to be deleted. Do I have to to call delete on them manually before the new assignment or is there another way to do this?

Upvotes: 0

Views: 73

Answers (1)

Jerry Krinock
Jerry Krinock

Reputation: 5020

As explained in the comments, it turns out that the Cascade Delete Rule does not delete a Group's Persons unless you delete the Group. So I've gutted my answer and replaced with this.

If you don't want to delete the Group, you must delete each Person and remove it from the relationship. It is not that bad, though…

if let people = group.people {
    for person in people {
        if let person = person as? NSManagedObject {
            managedObjectContext.delete(person)
        }
    }
}
group.mutableSetValue(forKey: "people").removeAllObjects()

NSBatchDeleteRequest might also work if you configured it with a predicate to filter only Persons in the relevant group, but unless you have thousands of Persons to delete I would not bother with it.

Upvotes: 1

Related Questions