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?
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-textobject.This is both a leak and an over-release. It’s the over-release that’s crashing.
Perhaps you meant this: