我一直在掙扎一段時間。我有一個標籤欄應用程序。在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];
}
- (IBAction爲)buttonCalc要計算number1和number2?我對嗎。 –
在buttonCalc中,我想計算一個數字1和數字2的和,並保存在其他地方(在另一個選項卡視圖中定義)。 –
查看我的帖子代碼 –