swift 3 - core data relationship - fetch data

空扰寡人 提交于 2019-12-25 16:09:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!