开发者

Return NSString from a recursive function

I have a recursive function that is designed to take parse a tree and store all the v开发者_开发知识库alues of the tree nodes in an NSString.

Is the algorithm below correct?

NSString* finalString = [self parseTree:rootNode string:@""];

-(NSString*)parseTree:(Node*)currentNode string:(NSMutableString*)myString
{
    [myString appendText:currentNode.value];

    for(int i=0;i<[currentNode.children length];i++){
        return [self parseTree:[currentNode.children] objectAtIndex:i] string:myString];
    }
}


No, it is not.

  1. You pass in @"" as the starting string. However, @"" is not an NSMutableString. This will certainly produce an exception when run.
  2. As soon as you return, then that method stops and you don't execute any more. This means that you go through the first iteration of the loop, you'll stop. Forever.
  3. You don't return anything if there are no children in the currentNode.
  4. There's no such method as appendText:. You probably mean appendString:

Here's another question: Why do you need to return a value at all? You're passing in an NSMutableString and modifying it, so why not just always modify it in place and not bother with a return value? For example:

- (void) parseTree:(Node*)currentNode string:(NSMutableString*)myString {
    [myString appendString:currentNode.value];

    for(Node * child in [currentNode children]){
        [self parseTree:child string:myString];
    }
}

And then invoke this with:

NSMutableString * finalString = [NSMutableString string];
[self parseTree:aNode string:finalString];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜