objective-c - 使用 Objective-C,有没有办法将树转换为快速枚举?

标签 objective-c ios fast-enumeration

如果有一棵树,它有一个rootNode,并且它的子节点指向左和右(二叉树),有没有办法将它转换成快速枚举,如 Objective-C 2.0?所以我们可以做

for (id node in [tree allNodes]) {
    // do something
}

最好不要为内存大小构造 O(n) 对象,而是使用集合对象,例如 NSMutableArrayNSSetNSDictionary .

顺序并不重要,但可能会以深度优先顺序出现。

最佳答案

当你实现快速枚举时,你不必一次返回所有元素。当然,如果您一次返回一个,您得到的只是快速枚举语法,没有太多性能优势。

您可以在每次调用 countByEnumeratingWithState:objects:count 时返回一个元素,或者您可以返回所有元素,甚至只返回 N 个元素。

例如,假设您有一棵大树。您可以使用传递给您的堆栈缓冲区及其长度:

NSUInteger numItemsToReturn = MIN(100, lengthOfStackBuffer);

然后,您可以继续遍历树直到 numItemsToReturn 或直到到达树的末端。

内部基础设施将继续调用 countByEnumeratingWithState:objects:count 直到它“看到”正确数量的元素。

但是请注意,如果您只返回部分数据,则必须将信息存储在 state 中,以便知道下次从哪里恢复。这就是 extra 的用途。

编辑

看到你对原贴的评论...如果你想支持快速枚举,那么很容易,如上所述。

但是,如果您只想遍历树来做一些事情,您可能需要考虑一个枚举 API。例如:

-(void)enumerateWithOptions:(MyTreeEnumerationOptions)options
                 usingBlock:^(id object, unsigned int level, BOOL isLeaf, BOOL *stop)block {
    // In here, you can use the options to determine if you are doing
    // pre/post depth first search, breadth-first, reverse, even concurrent.
    // You also provide an easy way to communicate to the caller not only the
    // object at this node, but the tree-depth of this node, whether it is a
    // leaf, and anything else you want to communicate.
}

然后用户可以调用:

[tree enumerateWithOptions:PreOrderDepthFirst
                usingBlock:^(id object, unsigned int level, BOOL isLeaf, BOOL *stop) {
    // Execute whatever code you want with this object...
    // Set *stop = YES to abort the enumeration.
}];

关于objective-c - 使用 Objective-C,有没有办法将树转换为快速枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302084/

相关文章:

ios - 在 NSMutableArray 的副本上使用快速枚举来删除对象的详细信息

ios - 崩溃 : AVAudioSession Notify Thread in iOS

iphone - 用图像填充自定义表格 View 单元格

iphone - 放大/缩小时 MKAnnotationView 错误更改了图钉图像

ios - 如何从 iOS 中的另一个类访问标签上的按钮?

objective-c - xcode objective-c 在 NSObject 上缺少 @end

objective-c - 在动画帧更改后使用变换缩放 UIView 会导致 UIView 在缩放之前跳回到原始帧

ios - 如何通过滑动 UITableViewCell 显示隐藏文本

ios - 如何在 iOS 上通过 UITextFields 进行枚举