views:

22

answers:

3

Hello,

I'm currently teaching myself Objective-C and Iphone Development using the very good 'Begining IPhone Development'. I have been playing around with one of the sample applications and I am trying to update one button with text from a text field when another button is pressed. I have set up my Actions and links and all that jazz. The code of the single method/function/call is below

-(IBAction)updateButtonPressed
{
NSString *newCaption = [[NSString alloc] initWithString:@"."];

newCaption = tfUpdateText.text;
[btnPressMe setTitle:newCaption forState:UIControlStateNormal];

[newCaption release];


}

It works perfectly the first time I press the button and maybe for two or three times after then crashes. I'm obviously doing something really stupid but I cant see it. This is all I added (as well as declarations, property - synthesize etc). Can someone point out my obvious memory leak.

Update:

If I change to this

-(IBAction)updateButtonPressed
{

[btnPressMe setTitle:tfUpdateText.text forState:UIControlStateNormal];



}

It works fine but could someone explain to me what mistake I was making?

+1  A: 

You're not using NSString properly here (and are really doing a lot more work than required). NSStrings are just pointers, so your second assignment to newCaption is just orphaning the first. When you then send [newCaption release] later on, you're not sending it to your alloc'd object, but rather to tfUpdateText.text, which you didn't retain. Get rid of the alloc and the release, and you should be all set.

Ben Gottlieb
Thanks, that makes it clearer.
Toby Allen
+2  A: 

You are incorrectly managing memory. What is the -initWithString:@"." for? You're generating a constant string @".", then leaking it, then pointing to a different string (tfUpdateText.text), then assigning that pointer to the title, then releasing the -text object.

This is both a leak and an over-release. It's the over-release that's crashing.

Perhaps you meant this:

-(IBAction)updateButtonPressed
{
    [btnPressMe setTitle:tfUpdateText.text forState:UIControlStateNormal];
}
Rob Napier
Thanks for the explanation
Toby Allen
+2  A: 

You have a memory management bug. The newCaption reference object you are releasing is different from the one you initialized. You are accidentally leaking the NSString you allocated, and releasing tfUpdateText.text instead.

You can remove the temperory variable like:

-(IBAction)updateButtonPressed
{
    [btnPressMe setTitle:tfUpdateText.text forState:UIControlStateNormal];
}
notnoop
And even if you weren't crashing here, the release of the tfUpdateText.text (which it appears, from this code, you don't own at this point) will cause further problems down the line.
mmc