ios - 无法使用 NSUserDefaults 保存整数

标签 ios objective-c nsuserdefaults

基本上,我试图做到这一点,以便在我重新启动应用程序时保存用户的分数,目前,在关闭并重新打开应用程序时,分数恢复为零。我在互联网上寻找了很多解决方案,但一无所获。这是我的代码 (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/

相关文章:

ios - 在运行时获取主 Storyboard

ios - 使用文件管理器迭代目录占用大量内存

arrays - 如何在 SwiftUI 的 @AppStorage 中存储嵌套数组

cocoa - 使用 NSUserDefaults 存储 NSTextView 的内容

ios - 使用 AVAssetWriter 将 UIImages 转为视频会产生 < 800 张图像的黑帧闪烁

iOS Safari 粘性输入底部不需要的空白

ios - 在 iOS 中从 0.pool.ntp.org 检索时间

objective-c - 如何检测鼠标是否位于菜单栏上?

objective-c - 检查用户是否在连续的 UISlider 上完成滑动?

objective-c - 从沙箱中的帮助程序读取 NSUserDefaults