为什么我无法检索我的plist文件?

时间:2013-08-19 21:38:40

标签: ios property-list

我有一个刚创建字符串的plist文件;它看起来像这样:

image of my plist file

这是我用来创建文件路径的代码:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //  Create a list of paths
NSString *documentsDirectory = [paths objectAtIndex:0]; //  Get a path to your documents directory from the list
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"NailServices.plist"]; //  Create a full file path

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) { //  Check if file exists
    //  Get a path to the plist created before in bundle directory (by Xcode)
    NSString *bundle = [[NSBundle mainBundle] pathForResource: @"NailServices" ofType: @"plist"];
    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //  Copy this plist to your documents directory
}

这是我用来检查数据的代码(以确保它正常工作)...我从NSLog语句中得到一个(null)返回)

//Load Dictionary with wood name cross refference values for image name
NSString *plistDataPath = [[NSBundle mainBundle] pathForResource:@"NailServices" ofType:@"plist"];
NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath];

NSLog(@"\nnailServicesDict: %@", NailServicesDictionary);

这是我第一次尝试创建/使用“字符串”plist文件;我已经阅读了我在Google和SO上找到的所有内容,而没有找到一个简单的'字符串文件的例子。我还需要做些什么才能获得这个plist数据?

2 个答案:

答案 0 :(得分:2)

您的问题是,当您的plist是NSArray时,您正在创建NSDictionary。因此,当您尝试将其创建为字典时,它将返回nil,因为不存在字典。

您需要更改:

NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath];

NSArray *NailServicesArray = [[NSArray alloc] initWithContentsOfFile:plistDataPath];

答案 1 :(得分:1)

作为发布的评论者,plist文件的根目录可以是NSArrayNSDictionary。您的示例plist的根目录为NSArray,因此您需要allocinit NSArray,而不是NSDictionary。如果在Xcode中构建应用程序时,plist存储在应用程序包中,并且您不需要在运行时修改它,则无需将其复制到NSDocumentsDirectory。另外,我建议使用[paths lastObject];而不是[paths objectAtIndex:0];,如果paths数组为空,则会引发异常。

相关问题