簡體   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