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 t开发者_如何学Pythonest 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];
}
}
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.
精彩评论