将NSMutableDictionary保存到plist iOS

时间:2012-09-30 11:48:32

标签: objective-c ios cocoa nsmutabledictionary save

这在过去的一天中变得非常令人沮丧 - 太多了:为什么这不起作用?

 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

1 个答案:

答案 0 :(得分:0)

您是否已将.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];

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