【问题标题】:I can read from a plist but fail to read from another one我可以从 plist 中读取,但无法从另一个 plist 中读取
【发布时间】:2015-10-29 03:30:44
【问题描述】:

我在我的支持文件中创建了两个名为 information.plist 和 data.plist 的 plist 文件,并将它们都添加到 Copy Bundle Resource。

我使用下面的代码从 plist 中读取数据。

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableDictionary* dictPlist = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:filePath];

并尝试显示 plist 中的数据:

NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSLog(@"%@", data1);

我从 information.plist 获取数据,但从 data.plist 获取“null”。

我错过了什么吗?

感谢您的帮助!

【问题讨论】:

  • 这两个 plist 文件在 app bundle 中,而不是 Documents 文件夹中。当然,除非您有其他代码复制了这些文件。
  • 但是为什么 information.plist 有效?以及如何将此文件复制到 Documents 文件夹?
  • 你从哪里读到的?捆绑包还是文档?
  • 当我发布这个应用程序时,我应该从 Document 中读取 plist?我说的对吗?
  • 没有。 Supporting Files 中的 plist 文件是应用程序包的一部分,而不是 Documents 文件夹。

标签: ios objective-c plist


【解决方案1】:

试试这个:

// Path of plist from bundle
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];

// Since your plist's root is a dictionary else you should form NSArray from contents of plist
NSDictionary *dataPlist = [NSDictionary dictionaryWithContentsOfFile:plistPath];

说明:您的 plist 在应用程序包中,而不是在 Documents 目录中,这就是您没有得到它们的原因。

【讨论】:

  • 如果您将 PLIST 放入支持文件中,那么您必须从包中读取它,正如我在代码中提到的那样。
  • ` NSString plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; NSMutableDictionary dictPlist = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:plistPath]; NSLog(@"----------------这是唯一的办法:%@",dictPlist); ` 再次为空。我正在用我的 iphone 进行测试,这有关系吗?
  • 请注意检查文件名,包括大小写。它必须是您的Supporting Files 文件夹中的data.plist。正如我上面建议的那样,在您的.app 文件中编译应用程序后,仔细检查data.plist 的存在。
  • 感谢您的帮助,对我来说意义重大。
  • 总是乐于提供帮助。它解决了您的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多