Verbe
Verbe

Reputation: 735

Using a for loop to concatenate strings

I'm quite new to Xcode and have a quite amateur question still, it's quite relevant. I come from VB.NET and if I want to print mylabel + mylabel(x10) i'd use the following code:

for(i=0,i<=10,i++) {
    mylabel = i;
    mylabel &= mylabel;
}

I'd like to do this for xcode as well...

what I currently have will overwrite the string instead of adding it:

for (int i=0; i<=10; i++) {
    NSMutableString *lol =
        [[NSMutableString alloc]initWithFormat:@" Getal: %i \n",i];
    [myLabel setStringValue:lol];
}

Upvotes: 0

Views: 4336

Answers (3)

Verbe
Verbe

Reputation: 735

Thank you, now I understand what the append is for and how to use it in the right way!

What I came up with was the following:

  [myLabel setStringValue:@""];
  for (int i=0; i<=10; i++) {
    NSMutableString *lol = [[NSMutableString alloc]initWithFormat:@"%@ Getal: %i \n",[myLabel stringValue],i];
    [myLabel setStringValue:lol];

Upvotes: -1

Caleb
Caleb

Reputation: 124997

Looks like you're trying to build a list of the indices? Try this:

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

If that's not exactly what you want, perhaps it'll get you started. Or, if you could give an example of the output you're looking for, someone might be nice enough to edit this.

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47699

If your intent is to create a string with 10 copies of "Getal: #" in it, on separate rows, you'd use something like this:

NSMutableString* result = [NSMutableString stringWithCapacity:150];
for (int i = 0; i < 10; i++) {
    [result appendFormat:@"Getal: %d\n", i];
}

Upvotes: 2

Related Questions