0

我是 iPhone 新手

我已经存储了GameData.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]);

    }
}

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

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

4

3 回答 3

1

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

请使用这行代码:

NSMutableDictionary *dict = [NSMutableDictionary alloc] init];

代替:

NSMutableDictionary *dict; 

它会解决你的问题。请让我知道您的反馈。

于 2012-12-06T12:07:52.013 回答
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]);

}
于 2012-12-06T12:45:54.267 回答
0

您需要初始化您的dict对象。

NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
于 2012-12-06T12:16:59.387 回答