【问题标题】:Generate plist with NSMutableDictionary使用 NSMutableDictionary 生成 plist
【发布时间】:2014-06-08 06:07:05
【问题描述】:

我在从 NSMutableDictionnary 生成 plist 文件时遇到问题。它似乎不起作用。我在 Stackoverflow 上看过很多例子。我从 plist 生成 Dictionary 但不是从 Dictionary 生成 plist。

这是我的代码:

NSArray *keys = [NSArray arrayWithObjects:@"id", @"name", nil];
NSArray *object = [NSArray arrayWithObjects:@"Value id", @"Value name", nil];
NSMutableDictionary *projectData = [NSDictionary dictionaryWithObject:object forKey:keys];

NSFileManager* fileManager = [NSFileManager defaultManager];


for (id key in projectData)
{
    NSLog(@"projectData = key : %@, value : %@", key, [projectData objectForKey:key]);
}


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"data.plist"];
NSLog(@"%@", plistPath);
//write
[projectData writeToFile:plistPath atomically:YES];
NSMutableDictionary *newDictionnary;

//read
if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"data.plist"])) {

    if ([fileManager isWritableFileAtPath:plistPath]) {
        [projectData writeToFile:plistPath atomically:YES];
        newDictionnary = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
        //NSLog(@"%@", plistPath);
    }
}

else {
    NSLog(@"File not found");
}
  for (id key in newDictionnary)
{
    NSLog(@"New dictionnary = key : %@, value : %@", key, [newDictionnary objectForKey:key]);
}

感谢您的帮助:)

【问题讨论】:

  • 因为你的键和对象都是数组,你可能想要 NSMutableDictionary *projectData = [NSDictionary dictionaryWithObjects:object forKeys:keys];而不是 NSMutableDictionary *projectData = [NSDictionary dictionaryWithObject:object forKey:keys];因为现在您将数组作为键对应于数组作为值。
  • 使用文字语法可能会更好:@{@"id":@"value-id", @"name":@"value-name"}
  • 在哪里?对于newDictionary ?

标签: ios objective-c dictionary plist


【解决方案1】:

请注意:您的 paths 变量从未使用过。

您不能直接写入您的捆绑目录。您必须写入文档文件夹、缓存文件夹或临时文件夹。

将[[NSBundle mainBundle] bundlePath] 替换为paths[0]。

【讨论】:

  • 我测试过,没有任何改变
  • 对不起,我是法国人。如果我使用[path[0]] 或[[NSBundle mainBundle] bundlePath],文件路径是相同的
  • 嗯,您的代码中有多个错误。你必须一个接一个地调试它们
  • 问题已解决。我没有打开我写入数据的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多