StringByAppendingString not concatenation
I am trying to take an array of strings and take each element and put it in string format. I wrote a method for this as I need to concatenate the listed array values into another string. For some reason I can't get the array values correctly, an empty string is returned.
- (NSString*)listParameters:(NSArray*)params
{
NSString *outputList = @"";
if (params) {
for (int i=0; i<[params count]; i++) {
NSLog(@"%@",[params objectAtIndex:i]);
[outputList stringByAppendingString:[params objectAtIndex:i]];
if (i < ([params count] - 1)) {
[outputList stringByAppendingString:@", "];
}
}
}
NSLog(@"outputList: %@", outputList);
return outputList;
}
The first log statement correctly returns a string (therefore there is a specific string in the array), but the second log statement only returns "outputList:".
I tried to make outputList start more than just an empty string, which didn't work. I also tried assigning to a [params objectAtIndex:i]
string and then adding it, didn't work either.
I feel like I'm missing something obvious here, but I can't seem to get it to work.
How can I get this array of strings to print on a single comma separated string?
source to share
You need to assign the result [outputList stringByAppendingString:[params objectAtIndex:i]]
and [outputList stringByAppendingString:@", "]
back to outputList
.
It would be better if you use an NSMutableString instance for outputList
this instead, as otherwise you will create a lot of auto-implemented objects in this loop.
source to share
You probably want to use NSMutableString with the appendString method. NSString is immutable.
- (NSString*)listParameters:(NSArray*)params
{
NSMutableString *outputList = [[NSMutableString alloc] init];
if (params) {
for (int i=0; i<[params count]; i++) {
NSLog(@"%@",[params objectAtIndex:i]);
[outputList appendString:[params objectAtIndex:i]];
if (i < ([params count] - 1)) {
[outputList appendString:@", "];
}
}
}
NSLog(@"outputList: %@", outputList);
return outputList;
}
source to share