我已经为此苦苦挣扎了一段时间。我有一个标签栏应用程序。在SecondView
我定义 number2 并将其保存到NSUserDefaults
我希望它在下次打开应用程序时被程序记住。在FirstView
我想做一些计算(并显示答案),其中包括之前保存的 number2。我无法让它工作。在代码中,我只留下了到目前为止有效的东西。任何帮助将不胜感激。
第一视图控制器.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController : UIViewController {
IBOutlet UILabel *labelAnswer;
}
-(IBAction)buttonCalc;
@property(nonatomic, retain) UILabel *labelAnswer;
@end
第一视图控制器.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
@synthesize labelAnswer;
-(IBAction)buttonCalc {
float number1 = 2;
//what should I put here (or somewhere else) to get number2 saved in second view?
float answer = number1;// + number2
labelAnswer.text = [[NSString alloc] initWithFormat:@"%f", answer];
}
SecondViewController.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController {
IBOutlet UITextField *textNumber2;
NSUserDefaults *defaults;
}
-(IBAction)buttonSave;
@property(nonatomic, retain) UITextField *textNumber2;
@end
第二视图控制器.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize textNumber2;
-(IBAction)buttonSave {
//saving my data
NSString *saveNumber2 = textNumber2.text;
defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:saveNumber2 forKey:@"savedNumber2"];
[defaults synchronize];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//loading my data
defaults = [NSUserDefaults standardUserDefaults];
NSString *loadNumber2 = [defaults objectForKey:@"savedNumber2"];
[textNumber2 setText:loadNumber2];
}