iOS:在本地保存高分

Loh*_*rdt 1 save ios

我想保留一个仅供本地使用的高分.一个int,它保持你的最高分,这样我就可以在新分数时对它进行测试.

你会推荐使用plist吗?

就像是:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Info.plist"];
NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];

versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,60,25)]; // for example
versionLabel.backgroundColor = [UIColor clearColor];
versionLabel.textColor = [UIColor whiteColor];
versionLabel.font = [UIFont systemFontOfSize:10];
NSString *versionString = [NSString stringWithFormat:@"v%@", [plistData objectForKey:@"CFBundleVersion"]];
versionLabel.text = versionString;
[self.view addSubview:versionLabel];
Run Code Online (Sandbox Code Playgroud)

这个数据会在下次打开应用程序时可用吗?

jms*_*617 5

恕我直言,最快速,最简单的事情就是使用NSUserDefaults.您可以获得读取/写入plist的速度,但您无需为单个值创建一个全新的文件.设置高分的代码如下所示.

[[NSUserDefaults standardUserDefaults] setInteger:100 forKey:@"high_score"];
Run Code Online (Sandbox Code Playgroud)

热潮,这就是你所需要的一切.然后,当你下次启动应用程序并希望检查高分时,可能是 - (void)gameEnded方法,或者 - (void)viewDidLoad,你只需说

NSInteger lastHighScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"high_score"];
Run Code Online (Sandbox Code Playgroud)

lastHighScore现在将是您先前保存的用户默认值中存储的值.如果密钥已存在,则使用setInteger:forKey:将覆盖先前的值.