我想使用在给定路径指定的文件中找到的键和值来创建和返回字典。我的桌面上有我的文件:ciudades.txt(一个人类可读的文件!!!没有xml,只是为了练习)。我的NSString需要使用哪种方法以及如何使用?请有人帮我填写我的代码XXXXXXX。提前致谢
- (NSMutableDictionary)ciudades
{
if (!ciudades) {
NSString *path = [NSString XXXXXXXXX];
ciudades = [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
答案 0 :(得分:1)
定义一个函数。
-(NSMutableDictionary*) ReadFileAsDictionaryForPath:(NSString* ) path
{
return [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
使用如下
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];
NSMutableDictionary* myDictionary = [self ReadFileAsDictionaryForPath:path];
if(!myDictionary)
{
NSLog(@"Error while reading data from file at path:%@",path);
}
答案 1 :(得分:0)
首先将该文件添加到应用程序包中通过将xcode中的现有文件添加到项目中。然后使用此方法获取文件路径,例如我正在获取图像的路径。
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"png"];
然后尝试使用dictionaryWithContentsOfFile方法查看它是否有效。