[英]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];
所以正確的工作流程應該是:
另請參閱“常用目錄”以獲取有關可以和應該保存應用程序數據的位置的詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.