0

澄清问题在这里。我最初试图使用以下stringByAppendingString方法连接两个字符串:

NSString *dataString = @",";
NSInteger i = 0;
NSString *cycleCountString = @"";
for (i = 0; i<[[self cycleList] count]; i++) {

    cycleCountString = [NSString stringWithFormat:@"cycle#%d,",i];
    [dataString stringByAppendingString:cycleCountString];
}
NSLog(@"DataString is: %@",dataString);

但是,NSLog 只是输出“ ,”,就好像cycleCountString没有附加到dataString.

阅读后:http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c ,我能够通过执行以下操作来解决问题stringWithFromat

NSString *dataString = @",";
NSInteger i = 0;
NSString *cycleCountString = @"";
for (i = 0; i<[[self cycleList] count]; i++) {

    cycleCountString = [NSString stringWithFormat:@"cycle#%d,",i];
    dataString = [NSString stringWithFormat:@"%@%@",dataString,cycleCountString];


}
NSLog(@"DataString is: %@",dataString);

知道为什么以前的方法不起作用吗?stringByAppendingString不像我想的那样工作?

谢谢!

4

4 回答 4

3

您永远不会更新 dataString 的值。

dataString = [dataString stringByAppendingString: cycleCountString];
于 2011-07-01T16:59:35.787 回答
1

NSString实例是不可变的——你不能改变它们。 stringByAppendingString:不会更改您的原始NSString实例,它会创建一个新实例NSString并返回它。

新版本有效,因为您将结果分配给stringWithFormat:to dataString。你可以让旧版本使用这样的东西:

dataString = [dataString stringByAppendingString:cycleCountString];
于 2011-07-01T17:01:22.997 回答
1

文档中的示例

NSString *errorTag = @"Error: ";
NSString *errorString = @"premature end of file.";
NSString *errorMessage = [errorTag stringByAppendingString:errorString];

产生字符串“错误:文件过早结束。”。

于 2011-07-01T17:02:01.287 回答
-1

因为你没有将 agian 分配给数据字符串

NSString *dataString = @",";
NSInteger i = 0;
NSString *cycleCountString = @"";
for (i = 0; i<[[self cycleList] count]; i++) {

    cycleCountString = [NSString stringWithFormat:@"cycle#%d,",i];

    dataString=[dataString stringByAppendingString:cycleCountString];//this Line
}

NSLog(@"DataString is: %@",dataString);

数据字符串为:,cycle#0,cycle#1,cycle#2,

于 2011-07-01T17:06:39.903 回答