问题
i work with core data and swift 3 for macOS.
- i have to entities: Person and Books
- I can create a person
- i can create a book which will assign to a person
- and i know how i can get the information which book is assign to which person with this code at the end
but how can i get the information which person has which book?
more details in my last post: swift 3 - create entry with relationship
Thank you very much :)
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!)")
}
回答1:
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: 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
来源:https://stackoverflow.com/questions/43867033/swift-3-core-data-relationship-fetch-data