Reputation: 1897
I'm trying to take an array of strings and take each item and put it into a string format. I wrote a method to do this as I need to concatenate the listed array values into another string. For some reason I cannot get the array values to list properly, a blank 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 properly returns a string (so there is definitely a string in the array), but the second log statement only returns "outputList: ".
I tried making outputList start as more than just an empty string which didn't work. I also tried assigning [params objectAtIndex:i]
to a string then appending it, didn't work either.
I feel like I'm missing something obvious here, but I cannot get it to work.
How can I get this array of strings to print into a single string separated by commas?
Upvotes: 3
Views: 1480
Reputation: 6027
You probably want to use a NSMutableString instead with its 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;
}
Upvotes: 8
Reputation: 6036
You need to assign the result of [outputList stringByAppendingString:[params objectAtIndex:i]]
and [outputList stringByAppendingString:@", "]
back to outputList
.
It would be better still if you were using an instance of NSMutableString for outputList
instead, as you're going to create a lot of autoreleased objects in that loop otherwise.
Upvotes: 4
Reputation: 5294
Try:
outputList = [outputList stringByAppendingString:@", "];
as stringByAppendingString works by returning a new String
Upvotes: 1