我有一个文本字段,您可以在一个视图控制器中填写,我想按下另一个视图控制器中的按钮,它会在该字段的末尾添加一些内容。所以目前我有:
CSExtracts.m
-(IBAction)savedataExtract:(id)sender{
NSString *savestringExtract = fieldExtract.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestringExtract forKey:@"savedstringExtract"];
[defaults synchronize];
}
-(IBAction)loaddataExtract:(id)sender{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstringExtract = [defaults objectForKey:@"savedstringExtract"];
[fieldExtract setText:loadstringExtract];
[label setText:loadstringExtract];
}
-(IBAction)KeyboardResponder{
[fieldExtract resignFirstResponder];
}
-(void)viewDidLoad{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring3 = [defaults objectForKey:@"savedstringExtract"];
[fieldExtract setText:loadstring3];
[label setText:loadstring3];
}
这基本上允许我输入一个文本框并保存并加载它。我在CSViewController中有一个按钮,按下时应该在这一行的末尾添加一行:
CSViewController.m
- (IBAction)addInt:(id)sender{
CSExtracts *viewA = [[CSExtracts alloc]initWithNibName:@"ViewA" bundle:nil];
NSString *textfieldtext = viewA->fieldExtract.text;
NSString *intvar = @"int varName;";
//NSString *currentStr = fieldExtract.text;
NSString *savestringExtract = [NSString stringWithFormat:@"%@ %@",textfieldtext, intvar];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestringExtract forKey:@"savedstringExtract"];
[defaults synchronize];
}
这可以改变字段中的文本,但是,应该是文本字段当前值的变量textfieldtext始终设置为null。这是为什么?
答案 0 :(得分:0)
文本字段中没有文字,因为在尝试获取文本值之前,尚未在CSExtracts控制器实例上调用 viewDidLoad ,因此无法从NSUserDefaults加载。
CSExtracts *viewA = [[CSExtracts alloc]initWithNibName:@"ViewA" bundle:nil];
//at this point viewDidLoad has not been called so textfieldtext = null
NSString *textfieldtext = viewA->fieldExtract.text;
您可以尝试向CSExtracts控制器添加属性
@property (nonatomic, copy) NSString *fieldExtractText;
然后在initWithNibName中:bundle:
- (id) initWithNibName: (NSString*) name bundle: (NSString*) bundleName
{
self = [super initWithNibName: name bundle: bundleName];
if(self){
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.fieldExtractText = [defaults objectForKey:@"savedstringExtract"];
}
return self;
}
在CSViewController中:
- (IBAction) addInt: (id) sender
{
CSExtracts *viewA = [[CSExtracts alloc]initWithNibName:@"ViewA" bundle:nil];
NSString *textfieldtext = viewA.fieldExtractText;
...
}