Objective-C 连接方法的差异
这里澄清问题。 我最初尝试使用 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
是否不像我想象的那样工作?
谢谢!
Clarification question here.
I was originally attempting to concatenate two strings using the stringByAppendingString
method:
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);
However, the NSLog was just outputing ",
" as if cycleCountString
was not being appended to dataString
.
After reading:http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c , I was able to fix the issue by instead doing a 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);
any idea why the previous method wasn't working? Does stringByAppendingString
not work the way I think it does?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您永远不会更新 dataString 的值。
You're never updating the value of dataString.
NSString
实例是不可变的 - 您无法更改它们。stringByAppendingString:
不会更改原始NSString
实例,它会创建一个新的NSString
并返回它。新版本之所以有效,是因为您将
stringWithFormat:
的结果分配给dataString
。你可以让旧版本使用这样的东西:NSString
instances are immutable - you can't change them.stringByAppendingString:
doesn't change your originalNSString
instance, it creates a newNSString
and returns that.The new version works because you assign the result of
stringWithFormat:
todataString
. You could make the old version work with something like this:文档中的示例
生成字符串“错误:文件过早结束。”。
Example in documentation
produces the string “Error: premature end of file.”.
因为你没有将agian分配给数据字符串,
数据字符串是:,cycle#0,cycle#1,cycle#2,
because u didn't assign agian to datastring
DataString is: ,cycle#0,cycle#1,cycle#2,