How to change this so that it returns arrays
The following code works perfectly and shows the correct output:
- (void)viewDidLoad {
[super viewDidLoad];
[self expand_combinations:@"abcd" arg2:@"" arg3:3];
}
-(void) expand_com开发者_StackOverflow社区binations: (NSString *) remaining_string arg2:(NSString *)s arg3:(int) remain_depth
{
if(remain_depth==0)
{
printf("%s\n",[s UTF8String]);
return;
}
NSString *str = [[NSString alloc] initWithString:s];
for(int k=0; k < [remaining_string length]; ++k)
{
str = [s stringByAppendingString:[[remaining_string substringFromIndex:k] substringToIndex:1]];
[self expand_combinations:[remaining_string substringFromIndex:k+1] arg2:str arg3:remain_depth - 1];
}
return;
}
However, instead of outputting the results, I want to return them to an NSArray. How can this code be changed to do that? I need to use the information that this function generates in other parts of my program.
There are several things that you need to change in your code.
- First - consider changing the name of your method to something more legible and meaningful than
-expand_combinations:arg2:arg3
. - Second - you have a memory leak. You don't need to set allocate memory and initialize
str
with the strings
, because you change its value right away in the loop without releasing the old value. - Third - take a look at
NSMutableArray
. At the beginning of the method, create an array with[NSMutableArray array]
, and at every line that you haveprintf
, instead, add the string to the array. Then return it.
basicaly you have:
create mutable array in viewDidLoad
before [self expand_combinations ...
add aditional parameter (mutable array) to expand_combinations
populate array in expand_combinations
精彩评论