我这里有这个代码,基本上它需要一个数组遍历每个项目并将其添加到一个带有逗号的字符串的末尾和循环之后,删除最后一个逗号:
NSString *areaDescriptionWSpaceCharacters = nil;
for(NSString *item in areaDescription)
{
[areaDescriptionWSpaceCharacters stringByAppendingString:[NSString stringWithFormat: @"%@,", item]];
}
areaDescriptionWSpaceCharacters = [areaDescriptionWSpaceCharacters substringToIndex:[areaDescriptionWSpaceCharacters length] - 1];
但areaDescriptionWSpaceCharacters返回nil
。为什么呢?
答案 0 :(得分:5)
您要将字符串附加到nil
。您需要首先将字符串初始化为空字符串。
NSString *areaDescriptionWSpaceCharacters = @"";
在这种情况下,您可以考虑使用NSMutableString
。
NSMutableString *areaDescriptionWSpaceCharacters = [NSMutableString string];
for (NSString *item in areaDescription) {
if (areaDescriptionWSpaceCharacters.length > 0) {
[areaDescriptionWSpaceCharacters appendString:@","];
}
[areaDescriptionWSpaceCharacters appendString:item];
}
或直接
NSString *areaDescriptionWSpaceCharacters = [areaDescription componentsJoinedByString:@","];
(这个任务很常见,有一种特殊的方法!)
答案 1 :(得分:1)
你的第一行本身就是罪魁祸首。你尚未初始化NSString,所以它总是为零。
NSString *areaDescriptionWSpaceCharacters;
或
NSString *areaDescriptionWSpaceCharacters = @"";
或
NSString *areaDescriptionWSpaceCharacters = [[NSString alloc] init];