我目前需要读取和写入 plist 文件。这是我目前的状态:我创建了一个名为“Scores.plist”的 plist 文件,并将它放在我的 xcode 项目的 Resources 文件夹中。plist 文件中包含一个带有键“Score”的字典。附加到键的对象是一个占位符值为 1010 的 NSNumber。当我运行我的代码时,我得到了奇怪的结果。我的 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);
}
}