2010-03-12 100 views
1

我有一个名为addHighScore的方法。当用户想要退出游戏时,他们可以保存得分。在资源文件夹中,我创建了一个highScore.plist并用一个条目填充它。其结构是:NSMutableArray/NSMutable字典不保存数据writeToFile

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]; 

} 

回答

4

的问题是,你正试图保存在应用程序包中的更改,但你没有权限写在那里。正确的地方来保存数据是在应用程序沙箱Documents目录 - 你可以得到它的路径:

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

所以,正确的流程应该是:

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

另请参阅"Commonly Used Directories"了解有关可以在哪里以及应该如何保存应用程序数据的更多信息。