删除拥有所有已分配书籍的人

delete person with all assigned books

我和 swift 4 一起工作 osx。

   let appdelegate = NSApplication.shared().delegate as! AppDelegate
    let context = appdelegate.persistentContainer.viewContext
    var people = [Person]()
    let request = NSFetchRequest<Person>(entityName: "Person")
    do {
       people = try context.fetch(request)
       for person in people {
           print("Person: ", person.name!)
           for book in person.books {
                print("Title: ", book.title!)   
           }           
       }
    }

catch { print(error) }

现在我想删除一个拥有所有已分配书籍的人。 我可以一步完成此操作,还是让我从实体书籍中请求每本书 objectID 并将其删除?我试过这样的事情:

   let appdelegate = NSApplication.shared().delegate as! AppDelegate
    let context = appdelegate.persistentContainer.viewContext
    var people = [Person]()
    let request = NSFetchRequest<Person>(entityName: "Person")


     people = try context.fetch(request)
       for person in people {
           context.delete(person as! NSManagedObject)
           for book in person.books {
                // request object ID of this book form books and delete it
           }           
       }


    } catch { }

Core Data 提供 "relationship delete rules"(请参阅 CoreData Programming Guide 中的关系删除规则部分)来控制删除对象时相关对象发生的情况。

在您的情况下,如果您将 Person 实体上的 books 关系的删除规则设置为 "Cascade",Core Data 将自动删除所有相关的 Book删除 Person.

时的对象