迅捷3-核心数据关系-提取数据 [英] swift 3 - core data relationship - fetch data
问题描述
我使用核心数据,并在macOS上使用swift 3.
i work with core data and swift 3 for macOS.
- 我必须拥有实体:人物和书籍
- 我可以创建一个人
- 我可以创建一本分配给某人的书
- 并且我知道如何才能获得该书分配给哪个人的信息,最后是此代码
但是我如何获得哪个人拥有哪本书的信息?
but how can i get the information which person has which book?
更多详细信息,请参见我的上一篇文章: swift 3 -创建具有关系的条目
more details in my last post: 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!)")
}
推荐答案
根据您的模型,一个人可以拥有一本书以上,因此您需要两个重复循环.
According to your model a person can have more than one book, so you need two repeat loops.
请注意,通用提取请求避免了显式类型转换,并将与成功提取相关的代码放入范围内.
Please note the generic fetch request which avoids the explicit type cast and put the code related to a successful fetch in the do
scope.
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) }
PS:如另一个问题所述,请考虑将模型中的title
和name
声明为非可选,以消除感叹号
PS: As mentioned in the other question consider to declare title
and name
in the model as non-optional to get rid of the exclamation marks
这篇关于迅捷3-核心数据关系-提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!