我是iphone新手
我有 storedGameData.plist 文件,在“root”字典下的“root”字典下,我有一个名为“gameProgress”的数组,我想在这个“gameProgress”数组中插入数据。
以下是我的代码
-(void)writeDataToPhone
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"storedGameData.plist"];
// read or create plist
NSMutableDictionary *dict;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( [fileManager fileExistsAtPath:plistPath] ) {
// Reading the Plist from inside the if
//statement
NSLog(@"dictionary existed, reading %@", plistPath);
dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
}
NSNumber *newNumberOfCompletedLevels = [NSNumber numberWithInt:1];
[dict setObject:newNumberOfCompletedLevels forKey:@"gameProgress"];
NSLog(@"writing to %@…", plistPath);
[dict writeToFile:plistPath atomically:YES];
NSLog(@"dictionary values are…:");
for (id key in dict) {
NSLog(@"key=%@, value=%@", key, [dict objectForKey:key]);
}
}
但是我的数组是空白的,没有插入任何东西
我的代码有什么问题?我应该在我的代码中更改什么以在数组中插入值
最佳答案
工作绝对没问题。 我就是这样,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"storedGameData.plist"];
// read or create plist
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( [fileManager fileExistsAtPath:plistPath] ) {
// Reading the Plist from inside the if
//statement
NSLog(@"dictionary existed, reading %@", plistPath);
dict = [NSMutableDictionary dictionary
}
NSNumber *newNumberOfCompletedLevels = [NSNumber numberWithInt:5];
[dict setObject:newNumberOfCompletedLevels forKey:@"gameProgress"];
NSLog(@"writing to %@…", plistPath);
[dict writeToFile:plistPath atomically:YES];
NSLog(@"dictionary values are…:");
for (id key in dict)
{
NSLog(@"key=%@, value=%@", key, [dict objectForKey:key]);
}
关于iphone - 在 Plist 文件中插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743014/