Can I use short code when initialize?

Discussion in 'iPhone/iPad Programming' started by mikezang, Jul 23, 2010.

  1. macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #1
    I have a very simple question. When I read iPad programming guide, there are a lot of similar codes as below:
    Code:
    NSString *str =  [[NSString alloc] initWithFormat:@"Row is %d", row];
    cell.textLabel.text = str;
    [str release];
    
    I want to know if I can use code as below:
    Code:
    cell.textLabel.text = [[NSString alloc] initWithFormat:@"Row is %d", row]
    
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    If you do that you will leak memory as you have called alloc/init to create an object thus "owning" it but you cannot call release on it as you do not keep a reference to it.

    I suggest you read, memorise and always follow the Cocoa Memory Management Rules.

    The following is OK:

    Code:
    cell.textLabel.text = [[[NSString alloc] initWithFormat:@"Row is %d", row] autorelease];
    
     
  3. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    As is:
    Code:
    cell.textLabel.text = [NSString stringWithFormat:@"Row is %d", row];
     
  4. thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #4
    Thanks for your answer.

    I also read what you suggested, maybe my English is not good enough, I am not sure about that so I want to confirm it.
     
  5. thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #5
    Thanks, this one is better!
     

Share This Page