views:

48

answers:

1

Hi,

I have this method and it's kind of really big so I can't include it in this post. It takes an array as parameter and tests its objects (NSStrings). Sometimes -but not always-, the method calls itself with an array containing one of those strings. If every test is passed, then the NSString is sent to another method which processes it. This all works fine but now I'm working on a different approach. I want to call the method and let it return an array of all NSStrings that passed the test successfully. But since the method calls itself I don't really know how to do this. Instead of processing it, I could add all successfully tested NSStrings to an array but that array would then needed to be accessible in all methods. What is recommended here? I would like to avoid public variables..

- (void)doStuff: (NSArray *)array { //A quick (very short) example of what I have now.
    for (NSString *string in array) {
        if ([string isEqualToString: @"test"])
            [self doStuff: [NSArray arrayWithObject: @"test2"]];
        else
            [self processStuff: string];
    }
}
+2  A: 

You can add a mutable array as one of its parameters and add the result there:

- (void)doRecursiveWithData:(NSArray *)array storeResultsIn:(NSMutableArray *)results { 
    if ( shoudGoDeeper ) 
       [self doRecursiveWithData:(your new array)];
    else 
       [results addObject:(whatever you want to store)]; // or use another method to so so
}

I know your example is just that, an example, but maybe it's worth thinking about how you can go without the recursion - in many ways that's easily doable and often performs better.

Eiko
The second parameter looks easy. I'll test it.I don't think that it's easily doable for my purpose to get it working without recursion.
Adam Lee
+1 - this is really the canonical way of doing this. But remember to pass the `results` array down into the recursive call! (Also worth noting the common variation where you have a simpler entry method that takes only the "real" input, which sets up the extra state variables -- `results` in this case -- and then calls through to the main recursive function which includes those state variables as params, finally unpacking or returning the results at the end.)
walkytalky