【问题标题】:Saving NSMutableDictionary to plist iOS将 NSMutableDictionary 保存到 plist iOS
【发布时间】:2012-09-30 11:48:32
【问题描述】:

这在过去一天变得非常令人沮丧,而且有点过分了:为什么这不起作用?

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",kAllScoresUnorderedArray]];

 NSMutableDictionary *test = [[NSMutableDictionary alloc] init];
 [test setObject:@"bob" forKey:@"tmo"];

 [test writeToFile:path atomically: YES];

我以前用过它,而且效果很好:我忘记在 info.plist 中添加什么了吗?这是我唯一能想到的。

感谢您的帮助!

编辑: 也许它与 Xcode 4.5 和 iOS6 有关?它适用于 4.3/iOS5

【问题讨论】:

  • 当说它不起作用时,你究竟是什么意思?它是否编译、是否崩溃、是否创建文件?
  • 另外,你为什么用stringWithFormat:而不是stringByAppendingPathExtension:
  • 这部分看起来有点可疑:[NSString stringWithFormat:@"%@.plist",kAllScoresUnorderedArray]。 kAllScoresUnorderedArray 中有什么?
  • @Till no,它不会崩溃,它只是继续运行,就好像代码不存在一样..
  • @PeterHosey 我从未听说过后者:我从教程中获得了代码,它以前对我有用。

标签: objective-c ios cocoa nsmutabledictionary save


【解决方案1】:

您是否已将 .plist 文件添加到您的项目中?如果是这样,试试这个:

NSError *error;
        NSFileManager *fileManager = [[NSFileManager alloc] init];
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",kAllScoresUnorderedArray]];

    if (![fileManager fileExistsAtPath: path])
            {
                NSString *bundle = [[NSBundle mainBundle] pathForResource:kAllScoresUnorderedArray ofType:@"plist"];

                [fileManager copyItemAtPath:bundle toPath: path error:&error];
            }

     NSMutableDictionary *test = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
     [test setObject:@"bob" forKey:@"tmo"];

     [test writeToFile:path atomically: YES];

如果没有,请在您的项目中创建属性列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2013-12-15
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多