插入Plist文件

时间:2012-12-06 11:50:19

标签: iphone objective-c ios plist

我是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]);

    }
}

但我的数组是空白的,没有插入任何内容

我的代码有什么问题?我应该在代码中更改什么来在数组中插入值

3 个答案:

答案 0 :(得分:1)

错误位于dict对象中。你还没有初始化它。

请使用以下代码行:

NSMutableDictionary *dict = [NSMutableDictionary alloc] init];

而不是:

NSMutableDictionary *dict; 

它会解决您的问题。请告诉我您的反馈意见。

答案 1 :(得分:1)

工作得非常好。 我只是这样做,

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]);

}

答案 2 :(得分:0)

您需要初始化dict对象。

NSMutableDictionary *dict = [NSMutableDictionary alloc] init];