繁体   English   中英

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

[英]Why can't I retrieve my plist file?

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

我的plist文件的图像

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

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数据?

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

你需要改变:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM