-1

我有一个文本字段,您可以在一个视图控制器中填写它,我想在另一个视图控制器中按下一个按钮,它会在该字段的末尾添加一些内容。所以目前我有:

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。为什么是这样?

4

1 回答 1

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;
    ...
}
于 2013-05-11T17:19:44.090 回答