Caption update on button causing IPhone app to crash
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 d开发者_JS百科oing 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 -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];
}
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];
}
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.
精彩评论