PDA

View Full Version : Can I use short code when initialize?




mikezang
Jul 23, 2010, 07:55 AM
I have a very simple question. When I read iPad programming guide, there are a lot of similar codes as below:

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:

cell.textLabel.text = [[NSString alloc] initWithFormat:@"Row is %d", row]



robbieduncan
Jul 23, 2010, 07:58 AM
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 (http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html).

The following is OK:


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

dejo
Jul 23, 2010, 09:05 AM
The following is OK:


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

As is:
cell.textLabel.text = [NSString stringWithFormat:@"Row is %d", row];

mikezang
Jul 23, 2010, 09:06 AM
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.

mikezang
Jul 23, 2010, 09:17 AM
As is:
cell.textLabel.text = [NSString stringWithFormat:@"Row is %d", row];
Thanks, this one is better!