Iphone Plist-flie中的插入
我不熟悉iphone 我已经存储了dGameData.plist文件,在“根”字典下的“根”字典下,我有一个名为“gameProgress”的数组,我想在这个“gameProgress”数组中插入数据 下面是我的代码Iphone Plist-flie中的插入,iphone,objective-c,ios,plist,Iphone,Objective C,Ios,Plist,我不熟悉iphone 我已经存储了dGameData.plist文件,在“根”字典下的“根”字典下,我有一个名为“gameProgress”的数组,我想在这个“gameProgress”数组中插入数据 下面是我的代码 -(void)writeDataToPhone { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString
-(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]);
}
}
但是我的数组是空的,没有插入任何内容
我的代码有什么问题?为了在数组中插入值,我应该在代码中做些什么更改呢?错误在
dict
对象中。您尚未初始化它
请使用这行代码:
NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
而不是:
NSMutableDictionary *dict;
这会解决你的问题。请告诉我您的反馈。您需要初始化
dict
对象
NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
工作非常好。
我只是喜欢
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是)
有时这也是一个原因。感谢您的回复,但plist文件中没有插入任何内容。请检查此项以在dict中插入值。NSString*NewNumberOfCompletedLevel=[NSString stringWithFormat@“%d”,1];[dict setObject:newNumberOfCompletedLevels-forKey:@“gameProgress”];
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]);
}