从URL到NSMutableArray的Plist

时间:2014-10-25 02:06:21

标签: ios objective-c plist nsdata nsurl

我有以下代码:

//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

1 个答案:

答案 0 :(得分: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)文件内容可以解析为数组。