Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController - KVO, UITableView and a "Tree"

I'm using a NSFetchedResultsController to implement KVO for my UITableView (which is obvious). What I can't figure out is, how to use multiple Entities - sort of a tree structure - to be present(ed) simultaneously.

Here is my setup:

  • Entity1
    • DisplayName
    • RelationToEntity2
  • Entity2
    • DisplayName

Now I can fetch the data of either to be presented - so far so good. What I want is to have a one-sectioned TableView (like a flattened view) with the following structure:

  • Entity1 (Entry 1)
  • Entity2 (Entry 1)
  • Entity2 (Entry 2)
  • Entity1 (Entry 2)

Though it might look like a thing to be done via sections, it's not. Both Entities should be a UITableViewCells. Can someone please point me the right direction to flatten the without loosing the actual hierarchy.

like image 972
gamma Avatar asked Jan 20 '11 13:01

gamma


1 Answers

It sounds like you need to maintain your own 'flattened' datasource. Perhaps the following will work:

When NSFetchedResultController tells you a new Entity1 has been inserted, you insert Entity1 and its associated Entity2s into say, _flattenedArray so it looks like this:

[<Entity1>, <related Entity2>, <related Entity2>...]

Where you insert them is up to you - it pretty much comes down to:

  1. construct a subarray containing the new Entity1 and associated Entity2 objects
  2. decide where in _flattenedArray to insert the new subarray.
  3. call reloadData or some other means to inform the tableView of the new data

When an Entity1 object is removed, remove it and all subsequent Entity2 objects until you encounter the end of _flattenedArray or run into another Entity1 object. This assumes Entity2 is never a "top level" object. If it is you will need to only remove those Entity2 objects in the relation.

When an Entity1 object gains or loses an Entity2 object, you can first delete the Entity1 object from _flattenedArray then reinserting it. If this is too efficient, do a merge instead.

like image 189
freespace Avatar answered Sep 30 '22 15:09

freespace