Reputation: 891
Can someone one explain to me why this code doesn't work? I have no problem sending the elements of an array to NSLog but they don't seem to be appending to the string. Do I have to cast the array elements to a string?
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSArray *dataarray=[JSON valueForKey:@"Data"];
NSLog(@"Response: %@", [JSON valueForKeyPath:@"Status"]);
NSString* output = [NSString stringWithFormat:@"response: %@",[JSON valueForKeyPath:@"Status"]];
int x;
for (x=0; x<[dataarray count]; x++) {
NSLog(@"%d : %@",x, [dataarray objectAtIndex:x]);
[output stringByAppendingFormat:@" %@ ",[dataarray objectAtIndex:x]];
}
//NSLog(@"%@", JSON);
NSLog(@"%@", output);
self.outPut2.text=output; }
Upvotes: 2
Views: 3270
Reputation: 14816
Your output
variable is an immutable NSString
. -stringByAppendingFormat:
doesn't append the new string in place, it returns a new string value that is the concatenation of the two original strings. You need to assign that value back to output
.
In the alternative, make output
an NSMutableString
, and then you can do the concatenation in place with -appendFormat:
.
Upvotes: 2
Reputation: 4304
You output
variable is set to be an inmutable string. So you can't directly add any content to it. You can create a new string using it's content and reassign it to itself, but you can't append new content.
You should try using NSMutableString and appendFormat or appendString
NSMutableString* output = [NSMutableString stringWithFormat:@"response: %@",[JSON valueForKeyPath:@"Status"]];
int x;
for (x=0; x<[dataarray count]; x++) {
NSLog(@"%d : %@",x, [dataarray objectAtIndex:x]);
[output appendFormat:@" %@ ",[dataarray objectAtIndex:x]];
}
Upvotes: 1
Reputation: 3937
The function
[output stringByAppendingFormat:@" %@ ",[dataarray objectAtIndex:x]];
returns a NEW string, without modifying the original, and you are not storing it anywhere. You should go like this:
output = [output stringByAppendingFormat:@" %@ ",[dataarray objectAtIndex:x]];
Upvotes: 3