在Xcode中创建一个plist文件

时间:2012-08-10 00:07:37

标签: iphone objective-c xcode

我正在保存/检索plist文件中的数据,但我有一个问题,如果它不存在,我无法创建plist文件。我需要在带有应用程序的Document文件夹中创建它。 我的代码是

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"playersnames.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"playersnames.plist"] ];

}

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];


NSFileManager *fileManager2 = [NSFileManager defaultManager];
//NSMutableDictionary *data;

if ([fileManager2 fileExistsAtPath: path])
{
    data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

}
else
{
    // If the file doesn’t exist, create an empty dictionary
    data = [[NSMutableDictionary alloc] init];

}

我搜索过来解决问题,但没有机会,我不知道代码中缺少什么。

如果有人可以向我解释如何操作,请。

我的代码在viewDidLoad中。

提前感谢。

1 个答案:

答案 0 :(得分:0)

您永远不会创建文件 - 将此第一个引用更改为fileExists:

if (![fileManager fileExistsAtPath: path])
{
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"playersnames.plist"] ];

}

到此:

if (![fileManager fileExistsAtPath: path])
{
    BOOL ret = [[NSDictionary dictionary] writeToFile:path atomically:YES];
    assert(ret); // better work!
}

现在您将创建该文件。稍后,您将需要通过稍后将完整字典保存到同一文件来执行相同的操作。重要说明:测试这些来电的退货代码!

相关问题