2017-05-09 108 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