如何在 Objective-C (iPhone) 中连接字符串?
可能的重复:
如何在 Objective-C 中连接字符串?
首先,平台是 iPhone,label.text 更改显示的标签。 考虑这种情况:
我有一个整数数组。 我想将它显示在屏幕上。
这是我的看法:
-(IBAction) updateText: (id)sender {
int a[2];
a[0]=1;
a[1]=2;
a[2]=3;
for (int i=0; i<=10;i++)
label.text = [NSString stringByAppendingString: [NSString stringWithFormat: @"%i", a[i]]];
}
正如你可能看到的,我很困惑。 请帮助我:(
Possible Duplicate:
How do I concatenate strings in Objective-C?
Firstly, the platform is iPhone and label.text changes the label displayed. Consider this scenario:
I've an array of integers. And I want to display it on the screen.
Here's my take on it:
-(IBAction) updateText: (id)sender {
int a[2];
a[0]=1;
a[1]=2;
a[2]=3;
for (int i=0; i<=10;i++)
label.text = [NSString stringByAppendingString: [NSString stringWithFormat: @"%i", a[i]]];
}
As you can probably see, I'm pretty confused. Pls pls help me out :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试这个:
Try this:
由于您使用的是循环,因此请务必谨慎对待 Tom 和 Benjie 的解决方案。 他们每个迭代都会创建一个额外的自动释放对象。 对于小循环来说,这很好,但如果循环的大小无限制或者字符串很大,则可能会导致非常大的内存峰值和性能损失。 特别是在 iPhone 上,这种循环可能会因短暂的内存峰值而导致令人惊讶的内存问题。
以下解决方案具有较小的内存占用量(速度也稍快并且键入的内容较少)。 请注意对
-appendFormat:
的调用,而不是-appendString
。 这可以避免创建将被丢弃的第二个字符串。 请记住,最终字符串末尾有一个多余的空格,您可能需要删除它。 您可以通过以不同方式处理第一次或最后一次迭代,或者通过修剪循环后的最后一个空格来解决此问题。不要忘记
[NSArray ComponentsJoinedByString:]
。 在这种情况下,您没有 NSArray,但在您有 NSArray 的常见情况下,这可能是获得您正在寻找的内容的最佳方法。Since you're using a loop, do be somewhat careful with both Tom and Benjie's solutions. They each create an extra autoreleased object per iteration. For a small loop, that's fine, but if the size of the loop is unbounded or if the strings are large, this can lead to a very large memory spike and performance hit. Particularly on iPhone, this is exactly the kind of loop that can lead to surprising memory problems due to short-lived memory spikes.
The following solution has a smaller memory footprint (it's also slightly faster and takes less typing). Note the call to
-appendFormat:
rather than-appendString
. This avoids creating a second string that will be thrown away. Remember that the final string has an extra space at the end that you may want to get rid of. You can fix that by either treating the first or last iteration differently, or by trimming the last space after the loop.Don't forget
[NSArray componentsJoinedByString:]
. In this case you don't have an NSArray, but in the common cases where you do, this is probably the best way to get what you're looking for.另一种不使用 NSMutableString 的方法:
这是一个完整的实现(更正您的范围):
您也可以这样做(例如,如果您想要一个逗号分隔的列表):
Another method without using NSMutableString:
Here's a full implementation (correcting your ranges):
You could also do it like this (e.g. if you wanted a comma separated list):