NSMutableArray始终返回null

时间:2012-01-02 12:33:43

标签: objective-c nsmutablearray plist nsdictionary

我的问题是当我在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文件时,我发现了我只插入一个

的数据 你可以帮我吗?

2 个答案:

答案 0 :(得分:1)

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

第二次搜索下载文件应更改为以下内容:

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

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

答案 1 :(得分:1)

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