我创建了一个简单的应用程序,它由 2 个 UILabel 和一个按钮组成,用于将它们的值相加。我NSUserdefaults
在退出应用程序/点击后退按钮/应用程序崩溃等时保存标签的值。我在选择将两个值相加的按钮时调用此保存函数。
我遇到的问题是只有一个 UILabel 值被保存,另一个没有。我已经尝试了各种调整,但无法深入了解它。
这是我的 h 文件代码:
#import <UIKit/UIKit.h>
int dcounter;
int dtotaler;
int enteramount;
@interface durood : UIViewController {
IBOutlet UILabel *dcount;
IBOutlet UILabel *dtotal;
IBOutlet UITextField *numberTextField;
}
-(IBAction)addtotal1;
这是我的 m 文件中的代码:
-(IBAction)addtotal1;{
float x = ([dcount.text floatValue]);
float y = ([dtotal.text floatValue]);
[dtotal setText:[NSString stringWithFormat:@"%g", x + y]];
dcounter=0;
dcount.text = [NSString stringWithFormat:@"%i",dcounter];
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSString stringWithFormat:@"%i",dtotaler] forKey:@"saveDtotal"];
[userDefaults setObject:[NSString stringWithFormat:@"%d",dcounter] forKey:@"saveDcount"];
[userDefaults synchronize];
-(void)saveDcount
{
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSString stringWithFormat:@"%d",dcounter] forKey:@"saveDcount"];
[userDefaults setObject:[NSString stringWithFormat:@"%d",dtotaler] forKey:@"saveDtotal"];
[userDefaults synchronize];
}
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDcount) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDcount) name:UIApplicationWillTerminateNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDtotal) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDtotal) name:UIApplicationWillTerminateNotification object:nil];
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
NSString *dcountString= [userDefaults objectForKey:@"saveDcount"];
NSLog(@"Your Dcount: %@",dcount);
NSString *dtotalString= [userDefaults objectForKey:@"saveDtotal"];
NSLog(@"Your Dtotal: %@",dtotal);
//checking if data in user defaults is not empty
if(dcountString.length>0)
{
dcounter=[dcountString intValue];
dcount.text = [NSString stringWithFormat:@"%d",dcounter];
}
else
{
//for first time
dcounter=0;
dcount.text=@"0";
}
if(dtotalString.length>0)
{
dtotaler=[dtotalString intValue];
dtotal.text = [NSString stringWithFormat:@"%d",dtotaler];
}
else
{
//for first time
dtotaler=0;
dtotal.text=@"0";
}
}
未保存的 UILabel / 字符串是“dtotal”。
任何帮助将不胜感激。谢谢。