I’m a newbie in objective-c.
I got a problem in saving a string from UITextField.
I declared a string in property and synthesize it which named “familyName” to store user’s family name.
Then I want to save the familyName when the user press a button.
-(IBAction)textFieldDidBeginEditing:(UITextField *)textField;
{}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
familyName = inputFamilyName.text;
NSLog(@"the user's family name is %@", familyName); //it works here.
if (inputFamilyName == textField) {
[inputFamilyName resignFirstResponder];
}
return YES;
}
-(IBAction)goToNameWheel:(id)sender{
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:familyName forKey:@"family"];
[userDefault synchronize];
}
It crashes when it runs the saving code, it said “Thread 1:EXC_BAD_ACCESS (code=1, address = 0x……”
After that, I try another test to see what happens to familyName, then I wrote:
-(IBAction)test:(id)sender{
NSLog(@"1.the family name is %@", inputFamilyName.text); // This works...
NSLog(@"2.the family name is %@", familyName);} // This crashes...
Finally… I try to retain familyName in textFieldDidBeginEditing:
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
familyName = inputFamilyName.text;
NSLog(@"the user's family name is %@", familyName); //it works here.
if (inputFamilyName == textField) {
[inputFamilyName resignFirstResponder];
}
[familyName retain]; // just added randomly...
return YES;
}
Then everything works fine, I can save the familyName, print it..etc..
My question is…what exactly happens here, why do I have to retain it? Anything wrong with my original code?
Thx for your time!
When you do
You’re not actually using the property. You’re using an instance variable with the same name as your property, but without the memory management stuff.
What you should be doing is
Then the property’s retain will kick in, and you won’t have to manually retain.
To make it harder to make the mistake, you could change your
@synthesizestatement to be:If you do that, then it means that the property called
familyNamewill have an instance variable called_familyNamebacking it — which means it’s a lot harder to accidentally type the wrong one accidentally, thus avoiding this mistake.