0

I'm trying to find a matching object in a tree, so I'm using ObjC fast enumeration. The problem is my method finds the matching value, hits the return line, and then sets the value to nil and keeps on iterating. Here's my method:

+ (INONode *)findByUUID:(NSString*)uuid fromRootNode:(INONode*)node
{    
    for (INONode * childNode in [node children]) {
        if ([[node uniqueID] isEqualToString:uuid]) {
            break;
        }
        else {
            [INONode findByUUID:uuid fromRootNode:childNode];
        }
    }

    return node;
}

When I follow code execution by setting a breakpoint, the break is hit, then goes to the return line, then back up to the statement that continues the iteration. What am I missing here?

Aaron Vegh
  • 5,217
  • 7
  • 48
  • 75

1 Answers1

5

Since your method is recursive, the return is returning you to the else branch of the if in your loop and continuing the search.

The way it is currently implemented, your method will only ever return the node passed in to it. The only return statement is return node, and node is never modified.

Here is one way you could do it:

+ (INONode *)findByUUID:(NSString*)uuid fromRootNode:(INONode*)node
{   
    // Check the root node
    if ([[node uniqueID] isEqualToString:uuid]) {
        return node;
    }

    // Check each child
    for (INONode * childNode in [node children]) {
        node = [INONode findByUUID:uuid fromRootNode:childNode];
        if (node) {
            return node;
        }
    }

    return nil;
}
monoxygen
  • 453
  • 3
  • 14
  • This can be confirmed by also looking at the call stack as the debugger progresses past each `return`. – dreamlax Jan 30 '13 at 01:40
  • So, dare I ask... what's the best way to get the *method* to return? Do I need to have the recursive method called from another method instead? – Aaron Vegh Jan 30 '13 at 03:11
  • You need to actually use the value returned by the recursive call. See my updated answer for one way you could do it. – monoxygen Jan 30 '13 at 05:51