我一直在努力解决这个问题。我有一个标签栏应用程序。在SecondView
我定义了number2并将其保存到NSUserDefaults
,因为我想在下次应用程序打开时由程序记住它。在FirstView
我想做一些计算(并显示答案),包括之前保存的number2。我无法让它发挥作用。在代码中,我只留下了迄今为止工作的东西。任何帮助将不胜感激。
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController : UIViewController {
IBOutlet UILabel *labelAnswer;
}
-(IBAction)buttonCalc;
@property(nonatomic, retain) UILabel *labelAnswer;
@end
FirstViewController.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
SecondViewController.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];
}
答案 0 :(得分:1)
用户,这可能对您有所帮助
-(IBAction)buttonCalc {
float number1 = 2;
//what should I put here (or somewhere else) to get number2 saved in second view?
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadNumber2 = [defaults objectForKey:@"savedNumber2"];
NSInteger number2=[loadNumber2 integerValue];
float answer = number1 + number2;
labelAnswer.text = [[NSString alloc] initWithFormat:@"%f", answer];
}
答案 1 :(得分:0)
您尝试在您的方法中使用以下代码,希望它能帮助您...
-(IBAction)buttonCalc {
float number1 = 2;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *strNumber2 = [defaults objectForKey:@"savedNumber2"];
float number2 = [strNumber2 floatValue];
//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];
}