从任意对象创建树结构
有时,创建类似树的结构对于您的对象来说很有用。一个简单的例子是表格视图中视图和行的关系。假设我们有一个表示表格视图的对象,并且我想添加一些章节和行。我们可以天真地创建一些数组和字典来存储这种结构,但是,如果我们能把这个结构精确地表示成我们想要构建的树,那不是更容易吗?
- TableView
- Section[0]
- Row[0]
- Row[1]
- Section[1]
- Row[2]
让我们根据 为什么
部分中提到的来构建这个树。假设我们有一个 TableView
、Section
和 Row
类,都是 PONSO
。正如标题中所说的,NODE
允许您从任何对象构建这种结构。
Row *row0 = [Row new];
Row *row1 = [Row new];
Section *section0 = [Section new];
[section0 node_addChildren:@[row0, row1]];
Row *row2 = [Row new];
Section *section1 = [Section new];
[section1 node_addChild:row2];
TableView *tableView = [TableView new];
[tableView node_addChildren:@[section0, section1]];
好的,现在您有了这棵树,您可以用它来做什么呢?
///Gets section0
Section *section = row0.node_parent;
///Gets an array @[row0, row1]
NSArray *rows = section.node_children;
///Gets the tableView object
TableView *tableView = [rows[0] node_root];
///Gets an array @[section0, tableView]
NSArray *ancestors = [rows[0] node_ancestors];
///Returns an index path of the row
NSIndexPath *indexPath = [row[0] node_indexPath];
///Returns row0
Row *row = [section0 node_nodeAtIndexPath:indexPath];
///And last but not least, you can print out the tree
[tableView node_debugDescription];
NODE
只是一个简单的 NSObject
类别。当您在任何对象上调用了 node_addChild:
方法,它创建了两个关联对象;一个创建在通过 node_addChild:
方法传递的对象上,另一个创建在调用的对象上。
这取决于您。这是一位 NSObject
上的类别,添加了关联对象,所以这是最危险的,但如果您正确地使用它,您应该没问题。前缀 node_
被添加,以最大限度地降低与其他库重名的风险,但您仍需要关注这一点。
pod 'NODE_'
非常欢迎拉取请求、问题和评论。
MIT,请查看 LICENSE 文件。