title: Core Data delete rule -- to-many relationship, delete when empty
body: <p>I'm a little fuzzy on how the delete rules for relationships in Core Data work, at least beyond the simple cases described in the documentation. </p>
  
  <p>Most of those cases, and most of the answers I've seen for questions here, use a model where the object on left side of a one-to-many relationship "owns" the objects on the right side: e.g. a <code>Person</code> has <code>PhoneNumber</code>s, and if you delete the person you delete all their associated numbers. In that kind of case, the solution is clear: Core Data will handle everything for you if you set the relationships like so:</p>
  
  <pre><code>Person      --(cascade)--&gt;&gt; PhoneNumber
  PhoneNumber --(nullify)--&gt;  Person
  </code></pre>
  
  <p>What I'm interested in is the opposite: A to-many relationship where the "ownership" is reversed. For example, I might extend the CoreDataBooks sample code to add an <code>Author</code> entity for collecting all info about a unique author in one place. A <code>Book</code> has one author, but an author has many books... but we don't care about authors for whom we don't list books. Thus, deleting an <code>Author</code> whose <code>books</code> relationship is non-empty should not be allowed, and deleting the last <code>Book</code> referencing a particular <code>Author</code> should delete that <code>Author</code>.</p>
  
  <p>I can imagine a couple of ways to do this manually... what I'm not sure of is:</p>
  
  <ul>
  <li>does Core Data have a way to do at least some of this automagically, as with relationship delete rules?</li>
  <li>is there a "canonical", preferred way to handle this kind of situation?</li>
  </ul>