I'm doing In-Order traversal of a Binary tree with a certain method executed on each node. I do this using a inOrderTraversalWithOperation:
method as shown below that uses a Block to define the function that is needed at each node.
-(void) inOrderTraversalWithOperation:(void (^) (BinaryTreeNode *))operation
{
[self.leftChild inOrderTraversalWithOperation:operation];
if (operation)
{
operation(self);
}
[self.rightChild inOrderTraversalWithOperation:operation];
}
Suppose I want to stop when the Block execution hits a certain condition. One way to do it is to make the inOrderTraversalWithOperation:
return a BOOL
, and make the Block return a BOOL
, as shown below.
But I am wondering if I can do it using the BOOL *stop
approach used by Apple in many of its APIs. How do the Blocks with that flag work "underneath"?
-(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;
}
EDIT
Based on Josh's comment it looks like BOOL *stop
will allow this but I still need inOrderTraversalWithStopOperation:
to return a 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;
}