问题描述
||
我想使用给定路径指定的文件中找到的键和值创建并返回字典。我的文件放在Desktop:ciudades.txt上(人类可读文件!没有xml,仅供练习)。我需要使用Nsstring的哪种方法以及如何使用?请有人帮我填写代码XXXXXXX。提前致谢
- (NSMutableDictionary)ciudades
{
if (!ciudades) {
Nsstring *path = [Nsstring XXXXXXXXX];
ciudades = [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
解决方法
首先将该文件添加到您的应用程序包中,方法是将xcode中的现有文件添加到您的项目中。然后使用这种方法来获取文件路径,例如,我正在获取图像的路径。
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@\"png\"];
然后尝试使用dictionaryWithContentsOfFile方法,看看它是否有效。
, 定义一个功能。
-(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);
}