simple for loop question.

Discussion in 'Mac Programming' started by kristiaand, Nov 4, 2008.

  1. kristiaand macrumors member

    Joined:
    Dec 5, 2007
    #1
    Hi All,
    its taking me longer to work this out than i thought and its driving me nuts i have to keep asking these stupid and simple questions...

    i have a simple for loop, and all i want todo is output an appended string to NSLog with the following info (eventually its going to populate an array instead. what i want to get showing in NSLog is

    entry 1
    entry 2
    entry 3

    but thanks to me not knowing how todo this i get

    entry
    entry
    entry

    heres my loop

    Code:
    NSMutableString *finalStringValue =[[NSMutableString alloc] init];
    	for (n = 1; n <= 3; n++)
    	{
    		[finalStringValue setString:@"entry "];
    		
    		[finalStringValue appendString:n];
    
    		NSLog(finalStringValue);
    	}
    	[finalStringValue release];
    
    
    now i know im going wrong on the FinalString append line i just cannot workout how to append an int to an NSString, am i going about this the wrong way? as i tried to use an NSNumber object for the loop but i got even more errors from the For loop at that point.
     
  2. kristiaand thread starter macrumors member

    Joined:
    Dec 5, 2007
    #2

    no matter i figured it out.. sorry to hassle you guys and gals.

    Code:
    [finalStringValue appendFormat:@"%d",n];
     
  3. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #3
    It looks like n is an integer, not a string type so you can't just append it to a string. Try using:

    Code:
    [finalStringValue setFormat:"%@ %d", @"entry", n];
    
    But, since you said you will be storing this in an array, I'd ditch the NSMutableString altogether as you will most likely run into undefined behavior since you will be changing the string after it's been added to the NSArray. What your doing can be done with an autorelease NSString via:

    Code:
    finalStringValue = [NSString stringWithFormat:"%@ %d", @"entry", n];
    
     

Share This Page