Trouble appendingStrings (NSString) within a for loop
Ok, so i'm pulling a list of addresses for a given postcode from an online datasource. The requests sends me a JSON of an array of arrays, within the first layer of the array are arrays of strings.
These contain for example.
Addressline1, Addressline2, Town, Country, Postcode
I need to add all of these strings together for each address, so that I have just 1 working string for each address. However, sometimes there is a blank field @""
within the arrays.
Here is my for loop.
id object;
NSString *startString = [NSString stringWithString:@"testStart:"];
for (object in arrayContainingAddress) {
NSString *useableString = [NSString stringWithFormat:@"%@", object];
if (![useableString isEqualToString:@""]) {
NSLog(@"%@", useableString);
[startString stringByAppendingString:useableString];
NSLog(@"%@", startString);
}
}
NSLog(@"%@", startString开发者_Go百科);
The problem is, startString is ALWAYS logging out at the end as 'testStart:', yet useableString logs to contain the correct addressline, town etc, The startString NSLog within the for loop also just logs out as 'testStart:'.
This entire chunk of code is sat inside a while loop which switches the 'arrayContainingAddress' for the appropriate array for each address.
The reason for the 'id object' is that my JSON conversion sometimes converts the values into NSNumbers (the first line of an address might be a house number, e.g. 123) and so I prevent a crash here.
TLDR: The string 'startString' is not being appended throughout my for loop.
stringByAppendingString
doesn't do anything to the string it is called on. It returns a new autoreleased string that is the concatenation of the two.
What you want to do is make your startString a mutable string:
NSMutableString *startString = [NSMutableString stringWithString:@"testStart:"];
then use the appendString
method:
[startString appendString:useableString];
You should change your code, as follows:
if (![useableString isEqualToString:@""]) {
NSLog(@"%@", useableString);
startString = [startString stringByAppendingString:useableString];
NSLog(@"%@", startString);
}
You were not updating the startString
in the loop.
精彩评论