How to Concatenate String in Objective-C (iPhone)? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-03 00:01:36

Try this:

NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
    [theString appendString:[NSString stringWithFormat:@"%i ",i]];
}
label.text = theString;

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.

NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
    [theString appendFormat:@"%i ",i];
}
label.text = theString;

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.

Kit
//NSArray *chunks   
string = [chunks componentsJoinedByString: @","];

Another method without using NSMutableString:

NSString* theString = @"";
for (int i=0; i<=10;i++){
    theString = [theString stringByAppendingFormat:@"%i ",i];
}
label.text = theString;

Here's a full implementation (correcting your ranges):

-(IBAction) updateText: (id)sender {
     int a[3];
     a[0]=1;
     a[1]=2;
     a[2]=3;
     NSString *str = @"";
     for (int i=0; i<3;i++)
       str = [str stringByAppendingFormat:@"%i ",i];
     label.text = str;
}

You could also do it like this (e.g. if you wanted a comma separated list):

-(IBAction) updateText: (id)sender {
     int a[3];
     a[0]=1;
     a[1]=2;
     a[2]=3;
     NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
     for (int i=0; i<3;i++)
         [arr addObject:[NSString stringWithFormat:@"%i",i]];

     label.text = [arr componentsJoinedByString:@", "];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!