繁体   English   中英

NSMutableArray / NSMutable Dictionary不在writeToFile上保存数据

[英]NSMutableArray/NSMutable Dictionary not saving data on writeToFile

我有一个名为addHighScore的方法。 当用户想要退出游戏时,他们可以保存他们的分数。 在resources文件夹中,我创建了一个highScore.plist并用一个条目填充它。 结构是:

   item 1 (array)
      Name (dictionary, string)
      Level (dictionary, string)
      Score(dictionary, Number)

我的问题是这样的:当我在模拟器中运行它时,在我加载arrHighScores然后添加newScore字典后,一切似乎都很好并且记录被添加(并通过NSLog语句显示)但这只是应用程序在跑。 退出后,返回,唯一存在的条目是我手动输入的条目。

当我在设备(iPhone)上运行它时,它永远不会显示添加的记录,即使仍然在游戏中。 我已经查看了关于NSDictionary的每个例子,但似乎无法弄清楚出了什么问题。

任何想法或建议都非常感谢。 在此先感谢您的帮助。 (GEO ...)

我的方法看起来像这样:

 -(IBAction) addHighScore {
    NSString *myPath = [[NSBundle mainBundle] pathForResource:@"highScores" ofType:@"plist"];
    NSLog(@"myPath: %@", myPath);
    NSMutableArray *arrHighScores = [[NSMutableArray alloc] initWithContentsOfFile:myPath];

    NSMutableDictionary *newScore = [[NSMutableDictionary alloc] init];
    [newScore setValue:@"Geo" forKey:@"Name"];
    [newScore setValue:lblLevel.text forKey:@"Level"];
    [newScore setValue:[NSNumber numberWithDouble: dblScore] forKey:@"Score"];

    [arrHighScores addObject:newScore];

    for (int i = 0; i < [arrHighScores count]; i++) {
        NSLog(@"Retreiving (%d) --> %@", i, [arrHighScores objectAtIndex:i]);
    }

    [arrHighScores writeToFile:myPath atomically:YES];

    NSMutableArray *tmpArray2 = [[NSMutableArray alloc] initWithContentsOfFile:myPath];

    NSSortDescriptor *mySorter = [[NSSortDescriptor alloc] initWithKey:@"Score" ascending:YES];
    [tmpArray2 sortUsingDescriptors:[NSArray arrayWithObject:mySorter]];    

    for (int i = 0; i < [tmpArray2 count]; i++) {
        NSLog(@"Retreiving (%d) --> %@", i, [tmpArray2 objectAtIndex:i]);
    }

    [arrHighScores release];
    [tmpArray2 release];
    [mySorter release];
    [newScore release]; 

}

问题是您试图在应用程序包中保存更改,但您没有权限在那里写。 保存数据的正确位置是应用程序沙箱中的Documents目录 - 您可以获取它的路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                             NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0];

所以正确的工作流程应该是:

  1. 尝试从Documents文件夹加载高分数据
  2. 如果文档文件夹中的文件不存在则从资源加载数据
  3. 更新数据
  4. 将数据保存到Documents文件夹

另请参阅“常用目录”以获取有关可以和应该保存应用程序数据的位置的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM