iOS Can I use short code when initialize?

mikezang

macrumors 6502a
Original poster
May 22, 2010
772
1
Tokyo, Japan
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]
 

robbieduncan

Moderator emeritus
Jul 24, 2002
24,638
61
Harrogate
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];
 

mikezang

macrumors 6502a
Original poster
May 22, 2010
772
1
Tokyo, Japan
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.