【发布时间】:2017-02-25 04:31:41
【问题描述】:
我正在使用在每个节点上执行的特定方法对二叉树进行按顺序遍历。我使用如下所示的inOrderTraversalWithOperation: 方法执行此操作,该方法使用块来定义每个节点所需的函数。
-(void) inOrderTraversalWithOperation:(void (^) (BinaryTreeNode *))operation
{
[self.leftChild inOrderTraversalWithOperation:operation];
if (operation)
{
operation(self);
}
[self.rightChild inOrderTraversalWithOperation:operation];
}
假设我想在 Block 执行达到某个条件时停止。一种方法是让inOrderTraversalWithOperation: 返回BOOL,并使Block 返回BOOL,如下所示。
但我想知道我是否可以使用 Apple 在其许多 API 中使用的 BOOL *stop 方法来做到这一点。带有该标志的块如何“在下面”工作?
-(BOOL) inOrderTraversalWithStopOperation:(BOOL (^) (BinaryTreeNode *))operation
{
BOOL shouldStop = NO;
shouldStop = [self.leftChild inOrderTraversalWithStopOperation:operation];
if (operation !=nil && shouldStop == NO)
{
shouldStop = operation(self);
}
if (!shouldStop)
{
shouldStop = [self.rightChild inOrderTraversalWithStopOperation:operation];
}
return shouldStop;
}
编辑
根据 Josh 的评论,BOOL *stop 似乎允许这样做,但我仍然需要 inOrderTraversalWithStopOperation: 来返回 BOOL
-(BOOL) inOrderTraversalWithStopOperation:(void (^) (BinaryTreeNode *, BOOL *))operation
{
BOOL shouldStop = NO;
shouldStop = [self.leftChild inOrderTraversalWithStopOperation:operation];
if (operation !=nil && shouldStop == NO)
{
operation(self, &shouldStop);
}
if (!shouldStop)
{
shouldStop = [self.rightChild inOrderTraversalWithStopOperation:operation];
}
return shouldStop;
}
【问题讨论】:
标签: objective-c tree objective-c-blocks