将NSNumber保存在plist中,而不是工作

 WSDRFCGFC_901 发布于 2023-02-13 14:42

所以我是Obj-C的新手(具有C和C++经验),我一直在努力.
很简单,我想保存并加载用户进度时的分数和级别.
我有3个功能getFilePath,loadDatasavaData.

getFilePathloadData似乎工作正常,但我不能获得saveData工作.

这是我的代码:

 -(void)saveData
 {
    NSNumber *updatedScore = [NSNumber numberWithInt:score];
    NSNumber *updatedLevel = [NSNumber numberWithInt:level];
    NSLog(@"The level im saving is %@",updatedLevel);
    NSLog(@"The score im saving is %@",updatedScore);
    NSMutableArray *value = [[NSMutableArray alloc]initWithObjects:updatedLevel,updatedScore, nil];
    [value writeToFile:[self getFilePath] atomically:YES];
}

-(NSString *)getFilePath
{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSLog(@"the path is %@",pathArray);
    return [[pathArray objectAtIndex:0]stringByAppendingPathComponent:@"saved.plist"];
}

我的NSLog消息返回正确的值,用户进展级别,但我无法保存它们.

1 个回答
  • 问题是该getFilePath方法是使用NSDocumentationDirectory而不是NSDocumentDirectory.不幸的是,Xcode的自动完成逻辑使得选择错误的逻辑非常容易.


    另外两个建议:

      您应该检查结果writeTofile,可能是这样的:

      NSArray *array1 = @[@1, @5, @3.423];
      BOOL success = [array1 writeToFile:path atomically:YES];
      NSAssert(success, @"%s: write failed", __FUNCTION__);
      

      就个人而言,由于我经常使用这种模式来创建一个引用NSDocumentDirectory目录中文件路径的字符串,因此我为它创建了一个代码片段,这使我无法输入错误的机会.它为我提供了几行代码的"自动完成"功能.所以,假设我的代码中有以下两行:

      NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
      NSString *path          = [documentsPath stringByAppendingString:<#filename#>];
      

      显然,使用你想要的任何代码,但关键是使用<#filename#>占位符作为参数stringByAppendingString.然后,如创建自定义代码片段文档(或参见NSHipster 关于该主题的讨论)中所述,您可以将这两行代码拖到片段库中,为它提供一个好名字(同样重要的是,一个好的快捷方式,我使用" documentsPath"作为我的快捷方式).现在,在将来,我可以documentsPath在我的代码中输入" ",然后我将会提示这两行代码.

      自从我开始使用这个特定的代码片段以来,我从来没有错误地意外地抓取错误的值而不是NSDocumentDirectory.

    2023-02-13 14:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有