主要思路:分解省、市、区,首先有一个最大的数组,是存放各个省的,省的数组里有省字典,省字典里有两个键值对,(provinceName:“北京”;cityArray[])。将省字典作为省数组的对象添加到省数组里。城市数组有两个键值对(cityName:“北京市”;areaArray:[])与省数组类似。
#import <Foundation/Foundation.h>
#import "Log.h"
int main(int argc, const char * argv[]) {
NSMutableArray *provinceArray = [NSMutableArray array];
//加载文件得到字符串
//参数1:文件路径
//参数2:编码格式
//参数3:错误信息
NSString *contentString = [NSString stringWithContentsOfFile:@"/Users/lanou3g/Downloads/area.txt" encoding:NSUTF8StringEncoding error:nil];
//NSLog(@"%@",contentString);
//以换行符分割字符串,得到每一行的字符串内容
NSArray *lineArray = [contentString componentsSeparatedByString:@"\n"];
for (NSString *lineString in lineArray) {
//前缀不是空格的话为省名
if (![lineString hasPrefix:@" "]) {
//创建一个省份字典
NSMutableDictionary *provinceDic = [NSMutableDictionary dictionary];
//省份字典添加键值对(provinceName:省份名)
[provinceDic setObject:lineString forKey:@"provinceName"];
//创建一个城市数组(用于后面存储城市字典)
NSMutableArray *cityArray = [NSMutableArray array];
//添加键值对(cityArray:城市数组)
[provinceDic setObject:cityArray forKey:@"cityArray"];
//将省字典添加到省数组中
[provinceArray addObject:provinceDic];
}
else if (![lineString hasPrefix:@" "]){
//前缀有空格且不是4个空格的话为城市名
//当读取到城市名的时候需要找到该城市所属的省份(ps:当前省份数组中最后一个元素就是当前城市所属省份)
NSMutableDictionary *provinceDic = [provinceArray lastObject];
NSMutableArray *cityArray = [provinceDic objectForKey:@"cityArray"];
//创建一个城市字典
NSMutableDictionary *cityDic = [NSMutableDictionary dictionary];
//添加键值对(cityName:城市名)
[cityDic setObject:lineString forKey:@"cityName"];
//创建地区数组(ps:后面用于存储地区名称)
NSMutableArray *areaArray = [NSMutableArray array];
//添加键值对(areaArray:地区数组)
[cityDic setObject:areaArray forKey:@"areaArray"];
//将城市字典存入到对应的城市数组中
[cityArray addObject:cityDic];
}else{
//前缀有空格且有4个空格的为地区名
//获取当前地区所属省份
NSMutableDictionary *provinceDic = [provinceArray lastObject];
//获取该省份的城市数组
NSMutableArray *cityArray = [provinceDic objectForKey:@"cityArray"];
//从当前城市数组中获取当前地区所属的城市
NSMutableDictionary *cityDic = [cityArray lastObject];
// 获取该城市的地区数组
NSMutableArray *areaArray = [cityDic objectForKey:@"areaArray"];
//将地区名存入该地区数组
[areaArray addObject:lineString];
}
}
//遍历省数组找到每一个省字典
for (NSMutableDictionary *provinceDic in provinceArray) {
NSLog(@"省份:%@",[provinceDic objectForKey:@"provinceName"]);
//遍历城市数组,根据省字典取出城市数组
for (NSMutableDictionary *cityDic in [provinceDic objectForKey:@"cityArray"]) {
NSLog(@"城市:%@",[cityDic objectForKey:@"cityName"]);
for (NSString *areaName in [cityDic objectForKey:@"areaArray"]) {
NSLog(@"地区:%@",areaName);
}
}
}
//遇到数组就遍历,遇到字典就根据键取值