我是objective-c的新手。我从 UITextField 保存字符串时遇到问题。
我在属性中声明了一个字符串并合成了一个名为“familyName”的字符串来存储用户的姓氏。然后我想在用户按下按钮时保存familyName。
-(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];
}
它在运行保存代码时崩溃,它说“线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x......”
在那之后,我尝试另一个测试来看看familyName会发生什么,然后我写道:
-(IBAction)test:(id)sender{
NSLog(@"1.the family name is %@", inputFamilyName.text); // This works...
NSLog(@"2.the family name is %@", familyName);} // This crashes...
最后...我尝试在 textFieldDidBeginEditing 中保留familyName:
-(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;
}
然后一切正常,我可以保存familyName,打印它......等等。我的问题是......这里到底发生了什么,为什么我必须保留它?我的原始代码有什么问题吗?谢谢你的时间!