我使用swift 4 for 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) }
现在我想删除所有已分配图书的人。 我可以一步完成这项工作,还是从实体书中请求每本书的对象ID并将其删除?我试过这样的事情:
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 { }
答案 0 :(得分:0)
核心数据提供&#34;关系删除规则&#34; (请参阅CoreData Programming Guide中的关系删除规则部分)以控制删除对象时相关对象发生的情况。
在您的情况下,如果您将books
实体上的Person
关系的删除规则设置为&#34; Cascade&#34;,Core Data将自动删除所有相关Book
删除Person
时的对象。