【问题标题】:Plist From URL to NSMutableArray从 URL 到 NSMutableArray 的 Plist
【发布时间】:2014-10-25 02:06:20
【问题描述】:

我有以下代码:

//Find device directory
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString  *documentsDirectory = [paths objectAtIndex:0];
            //Define file name
            NSString * fileName = [file objectForKey: (id) kCFFTPResourceName];
            //File path to file
            NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,fileName];
            //Download Plist from server and write to 'filePath'
            [[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url.net/directory/%@",[file objectForKey: (id) kCFFTPResourceName]]]] writeToFile:filePath atomically:YES];
            //Load Plist from directory
            NSURL *url = [NSURL URLWithString:filePath];
            //Load Data into Array
            mapDetails = [[NSMutableArray alloc ] initWithContentsOfURL:url];

            NSLog(@"Here is the Dict %@",mapDetails);

我的问题是,array 是否被返回为“nil”,我的问题是什么??

我尝试了各种组合,但仍然无法将PLIST 中的字符串转换为NSMutableArray

【问题讨论】:

  • 当代码不能按预期工作时,最好将长行分成多行。每行调用一个方法并将结果分配给一个变量。它使代码更易于阅读和调试。将包含 5 个方法调用的行拆分为 5 行单独的代码。

标签: ios objective-c plist nsdata nsurl


【解决方案1】:

[noSpaces stringByReplacingOccurrencesOfString:@"plist" withString:@""]; 返回一个新的NSString。它不会改变noSpaces

改变这两行:

[noSpaces stringByReplacingOccurrencesOfString:@"plist" withString:@""];

NSURL *url = [[NSBundle mainBundle] URLForResource:noSpaces withExtension:@"plist"];

到:

NSURL *url = [[NSBundle mainBundle] URLForResource:[noSpaces stringByReplacingOccurrencesOfString:@".plist" withString:@""] withExtension:@"plist"];

更新:为什么不使用 filePath 读取内容到NSMutableArray

NSURL *url = [NSURL URLWithString:filePath];

注意:

1) [[NSBundle mainBundle] URLForResource: withExtension:] 用于查找应用程序内置的资源。 2) 如果文件内容无法解析成数组,还是会得到nil

这假设文件位置是正确的。如果您所做的是加载远程 URL 并将内容保存到 plist 文件中,然后读取它,您应该确保 1)内容已成功保存到文件,2)加载它的路径正确,3)文件内容可以解析为数组。

【讨论】:

  • mapDetails 仍然返回 'nil' - 抱歉。
  • 您应该在mapDetails = ... 行设置断点并检查 url 值,并确保它与文件位置正确。
  • 更新主要问题帖子。我将如何“使用 filePath 将内容读取到 NSMutableArray”?对不起,我有点菜鸟:)
  • 我检查了 iOS 目录@JamesChan,Plist 就在里面。我将如何从目录中加载 Plist 并将其内容放入数组中?感谢您的帮助顺便说一句:)
  • 使用[NSURL URLWithString:filePath]作为文件URL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多