Question

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?

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top