开发者

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开发者_StackOverflow中文版 hierarchy.


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.


This is exactly the situation to use entity inheritance. When fetching a parent abstract entity with a fetched results controller all of the child entities can be displayed by the table. Use a section order property to display the sections in the order you prefer. And use a second sort property to order within the sections. The Notes app does this by fetching an abstract Container entity and displays Accounts and Folders which are child entities. It sections by Account and the first folder "All iCloud" cell is actually an Account. Folders have a relation to an account even though they are equals in the entity inheritance tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜