2017-05-09 110 views
0

我使用核心数据,swift 3使用macOS。swift 3 - 核心数据关系 - 获取数据

  • 我不得不实体:人与书籍
  • 我可以创造一个人
  • 我可以创建一本书,将分配给一个人
  • ,我知道我能得到相关信息,这本书是分配给哪个人与这段代码在最后

但我怎么能得到哪些人有哪些书的信息?

更多的细节在我的最后一个职位: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

根据模型中的一个人可以有不止一本书,所以你需要两个重复循环。

请注意通用获取请求,它避免显式类型转换,并将成功取回的代码放入do范围内。

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:由于在其他问题中提及考虑在模型中作为非可选申报titlename摆脱感叹号

+0

我喜欢这里 - 非常感谢你:) – Ghost108