我目前需要讀取和寫入plist文件。 這是我目前的狀態: 我創建了一個名爲「Scores.plist」的plist文件,我已將它放在我的xcode項目的Resources文件夾中。在plist文件中包含一個帶有「Score」鍵的字典。附加到密鑰的對象是一個佔位符值爲1010的NSNumber。 當我運行我的代碼時,我得到了奇怪的結果。 我的plist位於錯誤的地方嗎? 我聽說plist應該位於一些文檔目錄中,用於閱讀和書寫。但是,我不確定這是什麼,確切地說。 任何幫助表示讚賞。提前致謝! :)從plist文件中寫入和讀取
-(void)writeToPlistHighScore:(int)scoreNumber {
//attempt to write to plist
//however both the nslog's in this first section result in "null"
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Scores.plist"];
//NSString *scorePath2 = [[NSBundle mainBundle] pathForResource:@"Scores" ofType:@"plist"];
NSDictionary *plistDict = [[NSDictionary dictionaryWithContentsOfFile:filePath] retain];
NSLog(@"%@",[plistDict objectForKey:@"Score"]);
[plistDict setObject:[NSNumber numberWithInt:scoreNumber] forKey:@"Score"];
[plistDict writeToFile:filePath atomically: YES];
NSLog(@"%@",[plistDict objectForKey:@"Score"]);
[plistDict release];
//Stable code for reading out dictionary data
//this code reads out the dummy variable in Scores.plist located in my resources folder.
// Path to the plist (in the application bundle)
NSString *scorePath = [[NSBundle mainBundle] pathForResource:@"Scores" ofType:@"plist"];
NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:scorePath] retain];
NSString *scoreString = [NSString stringWithFormat:@"Score:%@", [plistData objectForKey:@"Score"]];
NSLog(@"%@",scoreString);
//checking to see where my file is...
//this logs a file path which I don't know means
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths objectAtIndex:0];
NSString *path = [documentsDirectory2 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",@"Scores"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){
NSLog(@"File don't exists at path %@", path);
NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:@"Scores" ofType:@"plist"];
[fileManager copyItemAtPath:plistPathBundle toPath: path error:&error];
}else{
NSLog(@"File exists at path:%@", path);
}
}