2014-11-21 41 views
1

我可以使用NSFetchedResultsController獲取一個實體並在單個部分的tableview中顯示數據。但是如何使用NSFetchedResultsController獲取兩個或更多個實體(無關係)並在不同部分顯示數據?CoreData:使用NSFetchedResultController獲取多個實體

我注意到,使用核心數據,我可以使用NSFetchedResultsController獲得行數和行數。我在NSFetchedResultsController中設置了一個實體,它很好地處理tableView,包括添加和刪除行。

func getFetchedResultController() - > NSFetchedResultsController { 
 
    fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) 
 
    fetchedResultController.delegate = self 
 
    fetchedResultController.performFetch(nil) 
 
    return fetchedResultController 
 
} 
 

 
func fetchRequest() - > NSFetchRequest { 
 
    let fetchRequest = NSFetchRequest(entityName: "Fruits") 
 
    let sortDescriptor = NSSortDescriptor(key: "desc", ascending: true) 
 
    fetchRequest.sortDescriptors = [sortDescriptor] 
 
    return fetchRequest 
 
} 
 

 
override func numberOfSectionsInTableView(tableView: UITableView) - > Int { 
 
    let section = fetchedResultController.sections ? .count 
 
    return section! 
 
} 
 

 
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) - > Int { 
 
    if let s = fetchedResultController.sections as ? [NSFetchedResultsSectionInfo] { 
 
    return s[section].numberOfObjects 
 
    } 
 
    return 0 
 
} 
 

 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell { 
 
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell 
 
    let fruit = fetchedResultController.objectAtIndexPath(indexPath) as Fruits 
 
    cell.textLabel.text = fruit.desc 
 
    return cell 
 
}

但部分始終爲零,因爲它僅使用一個實體。假設我想要顯示2個實體/表水果和飲料(無關係),我應該在哪裏將這些實體放在我的代碼中? NSFetchedResultsController可以在tableView的不同部分處理這些實體嗎?

+0

我找到了另一種方式來做到這一點,我讀[這裏](http://stackoverflow.com/questions/20337326/fetching-multiple-different-entities-from-the -same-core-data-database),但如果NSFetchedResultController可以做同樣的事情,我喜歡嘗試。這是可能的和如何? – 2014-11-21 09:02:23

+0

有關信息:如果您剛剛開始項目,則應嘗試Realm:http://realm.io。 Realm非常易於使用並且抽象了大量繁重的代碼。相同性能的代碼較少。 ;) – Pintouch 2014-11-21 09:23:12

+0

領域真棒!謝謝 – 2014-11-23 13:18:02

回答

1

使用 fetchedResultsControllers,說fruitFRCdrinksFRC,然後映射那些FRCS到indexPath通過的tableView使用報告的indexPath。例如,如果水果要出現在tableView的第0部分中,則可以使用tableView indexPathfruitFRC中查找以獲取水果詳細信息。但是對於飲料,TableView中的第1部分,你需要創建一個新的indexPath因爲drinksFRC將使用部分0(可以使用的NSIndexPathindexPathForRow:inSection:方法來創建新的indexPath。)

同樣,在numberOfRowsInSection ,如果section爲0,則返回fruitFRC中的對象數;如果section爲1,則返回drinksFRC中的對象數。

等等......

+0

這意味着我無法使用一個NSFetchedResultController來獲取多個實體來簡化我的代碼?謝謝你的答案btw。 – 2014-11-22 14:28:20

+0

基本上,這是正確的 - fetch或fetchedResultController將只檢索一個實體類型。但是,如果Fruit和Drink實體有很多共同的屬性,我想你可以將它們定義爲單個父實體(「Food」?)的單獨子實體,並獲取父實體。但是這可能比兩個FRC解決方案更復雜。 – pbasdf 2014-11-22 14:37:11

相關問題