1

我有一个我刚刚创建的字符串的 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 上可以找到的所有内容,但没有找到一个普通的 ol' 字符串文件的示例。我还需要做什么才能获得这个 plist 数据?

4

2 回答 2

2

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

你需要改变:

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

NSArray *NailServicesArray = [[NSArray alloc] initWithContentsOfFile:plistDataPath];
于 2013-08-19T21:53:30.087 回答
1

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

于 2013-08-19T21:48:37.210 回答