iphone - 在 Plist 文件中插入

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

    }
}

但是我的数组是空白的,没有插入任何东西

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

最佳答案

工作绝对没问题。 我就是这样,

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/

相关文章:

iphone - 使用 Parse 从应用程序内打开和关闭推送通知

iphone - AdWhirl(AdMob、iAd)广告未在已发布的 iPhone 应用程序中显示

html - 关闭 iPhone/Safari 输入元素舍入

iphone - 让 iPhone 振动

ios - ImageView |无法识别的选择器发送到实例 | Xcode 6.4 | iOS 8.4

iphone - 两个托管对象上下文可以共享一个持久存储协调器吗?

ios - NSPredicate 获取低于指定值的最大值

ios - 在 iOS 6 和 7 中打开应用程序设置页面

ios - 如何在 Xcode 4 中正确创建一个调整为文本长度的 UIButton?

ios - 类 "View controller"没有初始化程序