Search code examples
core-datansfetchedresultscontrollernsfetchrequest

Core Data - NSFetchRequestResult: count of items in one-to-many relationship from result?


Consider a Core Data model with two Entities: TermDictionary and Term. The TermDictionary has a "name" property, and a one-to-many relationship called "terms" which points to a set of Term objects, each of which consists of two properties: "name" and "score".

I've got an NSFetchRequest which I'm using as a data source for a UITableView which displays all of the TermDictionaries in the database. The idea is that the table will, for each cell, display the name of the dictionary, along with a count of the number of terms in that dictionary.

In the following code snippet, item contains an NSFetchRequestResult for the "TermDictionary" entity:

let thisDict = item as! TermDictionary
cell.textLabel?.text = thisDict.name
cell.detailTextLabel?.text = "\(thisDict.terms?.count ?? 0) terms"

...The table cells are correctly displaying the names of the Term Dictionaries, however it looks like thisDict.terms is always coming up nil, so the number-of-terms label always shows zero.

Do I need do do something special with item rather than just casting it to my TermDictionary managed object subclass?


Solution

  • You do not need to do anything special. If thisDict.terms prints as nil, it really is nil. Check your data store.