问题
I have a CoreData model that can contain an infinite number of children. And I want to display a list of each object, indented for readability like so
Object
Object first child
first childs children
first child children
Object second child
Object 2
Object also has children
MOre children
Childs
Now I come from a PHP background. and in PHP I would create a simple array which Ill traverse with some functions to build this list but this still seems stupidly hard for me.
I got a flat array which basically has items like this: array.name = @"Name"; array.children = nil or coredata rows array.parent = nil or coredata row
How do I traverse this and display a list indented and grouped like above.
Thanks in forward for any pointers or examples
-- Finished it with pointers below: resulting code as follows:
The resulting code is (similar to the following, I have my own adjustments but thats specifics)
- (NSArray *)flattenGroupsWithParent:(NSManagedObject<ECCGroup> *)parent {
//findGroupsForGroups gets all nodes with parent: parent.
NSArray *children = [dataSource findGroupsForGroup:parent];
for (NSManagedObject<ECCGroup> *child in children) {
ECCGroupNode *node = [[ECCGroupNode alloc] initWithGroup:child label:child.name];
[result addObject:node];
[result addObjectsFromArray:[self flattenGroupsWithParent:child]];
[node release];
}
}
The resulting array: result. contains an array, in order. with all parents -> children. In my case, indented where required. (using extra parameters not shown above)
回答1:
You start with a data model with one entity that would look something like:
Node{
name:string
parent<<-->Node.children
children<-->>Node.parent
}
To use you would do a fetch for all Node
objects whose parent
relationship was nil. That would be your top level objects. To find the next level of objects you would just query each top level object's children
attribute.
You indent rows using the UITableviewDelegate's tableView:indentationLevelForRowAtIndexPath:
method. In this case you would calculate the indent for each row by taking each node object and then walking it's parent relationship recursively all the way to the top and counting the steps.
However, on iOS, indented tableviews are discouraged. If you are targeting the iPhone, an indented tableview is next to useless because you don't have enough screen area to see a useful amount of the table. Instead, use a navigation controller to display a hierarchy of tableviews each displaying a different level of the data hierarchy.
来源:https://stackoverflow.com/questions/6788913/get-parent-child-array-from-coredata