1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

When to allocate?

Discussion in 'iPhone/iPad Programming' started by yrvaken2, Dec 16, 2008.

  1. macrumors newbie

    #1
    Can someone please explain the diffrence of the following and when to use what..?

    Code:
     NSString *string = [[NSString alloc] initWithFormat:@"hello"];
    and

    Code:
     NSString *string = @"hello";
    I am struggling a bit to get the hang of this memory efficient programing with releasing objects and stuff.
     
  2. macrumors regular

    xsmasher

    #2
    Code:
     NSString *string = [[NSString alloc] initWithFormat:@"hello"];
    //vs.
    NSString *string = @"hello";
    They differ in terms of memory management and flexibility. The second method, @"hello" , is a literal string - you don't need to retain or release it. It will always be around. Handy for creating constants. Even if you use this line in a loop, you are NOT creating a new object every time. There's only one @"hello" .

    The first one - the alloc/init - creates a new NSString object for you, which you manage (retain/release) as appropriate. Also, the init method you chose, initWithFormat, can take a format string a list of variables - so if you need to combine a list of variables into a string, you can use:
    Code:
    string = [[NSString alloc] initWithFormat:@"I lost my %@ in %@", bodyPart, city];
    
    You can't do that with the @ method - literal strings are defined when the program is compiled, not when it's running.

    I'd use the @"Hello" wherever I have a string that will always be the same every time I run my program, and the longer form whenever I need to construct a string that will be different every time I run my program.
     

Share This Page