基本上,我试图做到这一点,以便在我重新启动应用程序时保存用户的分数,目前,在关闭并重新打开应用程序时,分数恢复为零。我在互联网上寻找了很多解决方案,但一无所获。这是我的代码 (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
最佳答案
你可以使用这段代码,我希望它能为你工作:
[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:@"HighScore"];
关于ios - 无法使用 NSUserDefaults 保存整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768506/