【问题标题】:NSMutableArray always return nullNSMutableArray 总是返回 null
【发布时间】:2012-01-02 12:33:43
【问题描述】:

我的问题是当我在NSMutableArray 中读取 plist 文件的内容时总是返回 null

NSString *resourceDocPath = [[NSString alloc] initWithString:[[NSBundle mainBundle]bundlePath]] ;

// Create the new dictionary that will be inserted into the plist.

NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
[nameDictionary setValue:@"walid" forKey:@"id"];
[nameDictionary setValue:@"555 W 1st St" forKey:@"lien"];
NSString *r = [NSString stringWithFormat:@"%@/download.plist", resourceDocPath];
NSLog(@"%@",r);
// Open the plist from the filesystem.
NSMutableArray *plist = [NSMutableArray  arrayWithContentsOfFile:r]; 
 NSLog(@"%@",plist);
if (plist == NULL) 
{
    plist = [NSMutableArray array];
}
[plist addObject:nameDictionary];
 NSLog(@"%@",plist);
[plist writeToFile:r atomically:YES];

当我查看 plist 文件时,我发现我只插入了一个数据

你能帮帮我吗?

【问题讨论】:

    标签: objective-c nsmutablearray plist nsdictionary


    【解决方案1】:

    您正在尝试访问应用程序包而不是文档目录,该目录可以通过NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"]; 访问。捆绑包无法修改,因此创建的数组永远不会保存,因此永远不会加载它。

    【讨论】:

      【解决方案2】:

      首先你不应该检查plist == null,而是检查plist == nil

      二次搜索下载文件应改为如下:

      NSURL *url = [[NSBundle mainBundle] URLForResource:@"download" withExtension:@"plist"];
      NSMutableArray *plist = [NSMutableArray arrayWithContentsOfURL:url];
      

      第三: 我认为扩展名为 plist 的文件不会返回数组。
      它可能代表一本字典。尝试创建 NSMutableDictionary 而不是数组。

      【讨论】:

      • 请问如何创建 NSMutableDictionary 而不是数组?
      • 对于每个有自己喜欢的答案的问题(包括我的!),单击答案旁边的勾的轮廓,它应该会变成绿色。
      • NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfURL:url];
      • 当我查看 app 文件夹中 plist 文件的内容时,我发现每次运行 app 时文件都是空的,为什么?
      • 您不允许更改捆绑包中的文件。您可能最好在文档目录或库目录中创建一个文件,如“jrtc27”所述。 (见其他答案)
      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 2014-03-04
      • 2016-11-02
      • 2014-05-06
      • 2012-06-05
      • 2014-05-30
      • 2014-02-23
      • 2017-10-12
      相关资源
      最近更新 更多