Search code examples
iphoneiosios4core-dataentity-relationship

Is it possible to delete unreferenced objects automatically in Core Data?


My data model contains two entities: Author and Book with a one to many relationship (one author may write several books).

Let's say that there are only two books and two authors in DB as follows:

  • Book A is assigned to Author X
  • Book B is assigned to Author Y

Assuming following change is applied:

  • Book B is assigned to a new Author Z.

Result:

  • Author Y exists in DB but points to no book.

My question: is it possible to configure the data model so objects like Author Y will be automatically deleted when they are not referenced by any book?


Solution

  • You will need to determine "orphaned" books manually.

    When you update the Author relationship you could check the old Author's books relationship to see if it still has any books.

    Alternatively you could use notifications to determine when the NSManagedObjectContext changes: NSManagedObjectContextObjectsDidChangeNotification. If you register for this notification you can check for a number of changes to Author objects. Have a look at that specific notification in the docs.