在 for 循环中添加字符串 (NSString) 时出现问题
好的,我正在从在线数据源中提取给定邮政编码的地址列表。请求向我发送一个数组数组的 JSON,数组的第一层是字符串数组。
这些包含例如。
Addressline1, Addressline2, Town, Country, Postcode
我需要将每个地址的所有这些字符串添加在一起,这样每个地址只有 1 个工作字符串。然而,有时数组中会有一个空白字段@""
。
这是我的 for 循环。
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);
问题是,startString 总是在最后以“testStart:”的形式注销,但 useableString 日志包含正确的地址行、城镇等,for 循环中的 startString NSLog 也只是以“testStart:”的形式注销。
整个代码块位于 while 循环内,该循环将“arrayContainingAddress”切换为每个地址的适当数组。
“id 对象”的原因是我的 JSON 转换有时会将值转换为 NSNumbers(地址的第一行可能是门牌号,例如 123),因此我在这里防止崩溃。
TLDR:在我的 for 循环中没有附加字符串“startString”。
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);
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
stringByAppendingString
不会对调用它的字符串执行任何操作。它返回一个新的自动释放字符串,它是两者的串联。您想要做的是将 startString 设为可变字符串:
然后使用
appendString
方法: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:
then use the
appendString
method:您应该更改代码,如下所示:
您没有更新循环中的
startString
。You should change your code, as follows:
You were not updating the
startString
in the loop.