基本上我试图这样做,当我重新启动应用程序时,用户的分数被保存,目前,在关闭并重新打开应用程序时,分数会恢复为零。我在互联网上寻找了很多解决方案但却一无所获。这是我的代码(ViewController.m):
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
int bytes;
int highScore;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
highScore = bytes;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Snippet used to get your highscore from the prefs.
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)addBytes:(id)sender {
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
highScore++;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[_byteCounter setText:[NSString stringWithFormat:@"%d", highScore]];
}
@end
答案 0 :(得分:2)
你可以使用这段代码,我希望能为你工作:
[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@“HighScore”];
答案 1 :(得分:0)
用户默认值未更新,因为您没有更新它。
highscore ++只增加你的int变量,它不会增加NSUserDefaults中的值。因此,在更新高分后,您仍需要通过调用:
来更新NSUserDefaults[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
此外,您不需要也不应该调用同步。稍后将自动将数据刷新到磁盘上。
答案 2 :(得分:0)
启动时,我没有将保存的值从NSUserDefaults显示到标签,这是我更新的代码,它会在重新启动应用程序时保存整数。 (我为自己感到骄傲!)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
int bytes;
int highScore;
- (void)viewDidLoad {
[super viewDidLoad];
highScore = bytes;
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
[_byteCounter setText:[NSString stringWithFormat:@"%d", highScore]];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (IBAction)addBytes:(id)sender {
highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"HighScore"] intValue ];
highScore++;
[_byteCounter setText:[NSString stringWithFormat:@"%d", highScore]];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"HighScore"];
}
@end