对于省市区的问题,关键在于搞清楚数组嵌套字典,字典里面装数组的多重嵌套关系,沉下心来,捋清楚思路,

实在看不懂就多打几遍,这道题理解了,熟练了对之后学习很有好处。

代码如下:

NSString *path = @"/Users/lan/Desktop/省市区/省市区/area.txt";    //导入省市区文本的路径

NSString *pathStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    //通过UTF8转码,将省市区装入到字符串中

 NSArray *array = [pathStr componentsSeparatedByString:@"\n"];      //根据回车符号“\n”,将字符串切割成数组

NSMutableArray *arrayProvince = [NSMutableArray arrayWithCapacity:0];  //创建初始化一个可变数组

 for (NSString *str in array) {  //遍历数组

if (![str hasPrefix:@" "]) {     //判断非空格字符,找出省(由于省的名字前没有空格)

//每找到一个省的名字,创建一个字典

NSMutableDictionary *proDic = [NSMutableDictionary dictionaryWithCapacity:0];

//将省的名字放入字典当中,并设置key为ProName

[proDic setObject:str forKey:@"ProName"];

//创建市的数组,存放市区的字典

NSMutableArray *cityArray = [NSMutableArray arrayWithCapacity:0];

//将数组存入省的字典中

[proDic setObject:cityArray forKey:@"cityArray"];

//将省字典放入省的字典中

[arrayProvince addObject:proDic];

}

//找到市的名字

else if ([str hasPrefix:@"  "] && ![str hasPrefix:@"    "]){

//找到隶属的省的字典

NSDictionary *proDic = [arrayProvince lastObject];

//将省字典中预留的市的数组找出来

NSMutableArray *cityarr = [proDic objectForKey:@"cityArray"];

//创建市的字典

NSMutableDictionary *cityDic = [NSMutableDictionary dictionaryWithCapacity:0];

//把市的名字写入到市的字典中

[cityDic setObject:str forKey:@"cityName"];

//创建区的数组,用来存放找到的区的名字

NSMutableArray *zoneArray = [NSMutableArray arrayWithCapacity:0];

//把区的数组,放入到市的字典中

[cityDic setObject:zoneArray forKey:@"zoneArray"];

//把市的字典放入到市的数组中

[cityarr addObject:cityDic];

}

else{

//找到隶属的省的字典

NSDictionary *proDic = [arrayProvince lastObject];

//将省字典中预留的市的数组找出来

NSMutableArray *cityarr = [proDic objectForKey:@"cityArray"];

//将市数组中的市的字典找到

NSDictionary *citDic = [cityarr lastObject];

//将市字典中的区的数组找到

NSMutableArray *zoneArray = [citDic objectForKey:@"zoneArray"];

[zoneArray addObject:str];

}

for (NSMutableDictionary *dic1 in arrayProvince) {    //遍历打印

NSLog(@"%@",[dic1 objectForKey:@"ProName"]);

for (NSMutableDictionary *dic2 in [dic1 objectForKey:@"cityArray"]) {

NSLog(@"%@",[dic2 objectForKey:@"cityName"]);

for (NSString *str in [dic2 objectForKey:@"zoneArray"]) {

NSLog(@"%@",str);

}

}

}

05-08 08:44