我使用核心数据和swift 3 for macOS。
但我怎样才能获得哪个人拥有哪本书的信息?
我上一篇文章中的更多详情:swift 3 - create entry with relationship
非常感谢:)
let appdelegate = NSApplication.shared().delegate as! AppDelegate
let context = appdelegate.persistentContainer.viewContext
var books = [Book]()
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Book")
do {
books = try context.fetch(request) as! [Book]
} catch { }
for book in books {
print("Title: \(book.title!)")
print("Person: \(book.person!.name!)")
}
答案 0 :(得分:0)
根据你的模特,一个人可以有一本以上的书,所以你需要两个重复循环。
请注意通用提取请求,该请求可避免显式类型转换,并将代码与<{1>}范围内的成功提取相关联。
do
PS:正如在另一个问题中提到的那样,考虑将模型中的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) }
和title
声明为非可选的以消除感叹号