0

我已经为此苦苦挣扎了一段时间。我有一个标签栏应用程序。在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];
}
4

2 回答 2

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];
}
于 2012-11-24T06:02:29.350 回答
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];
}
于 2012-11-24T05:59:32.310 回答