Objective-C 中如何用数组和字典存储城市地区的代码

//将文件转换成字符串
    //参数1:文件路径
    //参数2:编码格式
    //参数3:错误信息
    //NSError *error = nil;
    NSString * contentString = [NSString stringWithContentsOfFile:@"/Users/lanou3g/Desktop/7.19/C06_省市区/C06_省市区/area.txt" encoding:NSUTF8StringEncoding error:nil ];

 //创建省份数组
    NSMutableArray *provinceArr = [NSMutableArray array];
 //分割字符串(以换行符分割字符串,得到每一行字符串内容)
    NSArray * lineArray = [contentString componentsSeparatedByString:@"\n"];
    for (NSString *lineString in lineArray) {
       // NSLog(@"line:%@",lineString);
        if (![lineString hasPrefix:@" "]) {
            //前缀不是空格的话为省名
            //创建一个省份字典
            NSMutableDictionary * provinceDic = [NSMutableDictionary dictionary];
           
            //省份字典添加键值对(provinceName:省份名)
            [provinceDic setObject:lineString forKey:@"provinceName"];
            //创建一个城市数组(ps:用于以后存储城市字典)
            NSMutableArray * cityArray = [NSMutableArray array];
            //添加键值对(cityArray:城市数组)
            [provinceDic setObject:cityArray forKey:@"cityArray"];
            //将省字典添加到省数组中
            [provinceArr addObject:provinceDic];
        }else if (![lineString hasPrefix:@"    "]){
             //前缀有空格且不是4个空格的话为城市名
            //当读取到省市名的时候需要找到该市所属的省份(ps:省份数组中最后一个元素就是当前所属省份)
            NSMutableDictionary *provinceDic =[provinceArr lastObject];
            NSMutableArray * cityArr = [provinceDic objectForKey:@"cityArray"];
            //创建城市字典
            NSMutableDictionary * cityDic = [NSMutableDictionary dictionary];
            //添加键值对(ciytyName:城市名)
            [cityDic setObject:lineString forKey:@"cityName"];
            //创建地区数组(p-s:后面用于存储地区名称)
            NSMutableArray *areaArray = [NSMutableArray array];
             //添加键值对(areaArray:地区数组)
            [cityDic setObject:areaArray forKey:@"areaArray"];
            //将城市字典存储到对应的城市数组中
            [cityArr addObject:cityDic];
        }else {
            //前缀有空格且是4个空格的话为地区名
            //获取地区属省份
            NSMutableDictionary *provinceDic = [provinceArr lastObject];
            //获取该省份的城市数组
            NSMutableArray * cityArr =[provinceDic objectForKey:@"cityArray"];
            //从城市数组中获取当前地区所属的城市
            NSMutableDictionary * cityDic = [cityArr lastObject];
            //获取该城市的地区数组
            NSMutableArray * areAarray = [cityDic objectForKey:@"areaArray"];
            [areAarray addObject:lineString];
        }
        
    }
   //NSLog(@"%@",provinceArr);
   // forin遍历省数组名
    for (NSMutableDictionary * provinceDic in provinceArr) {
        NSLog(@"省份:%@",[provinceDic objectForKey:@"provinceName"]);
        for (NSMutableDictionary *cityDic in [provinceDic objectForKey: @"cityArray"]) {
            NSLog(@"市:%@",[cityDic objectForKey: @"cityName"]);
            for (NSString * areaName in [cityDic objectForKey:@"areaArray"]) {
                NSLog(@"地区:%@",areaName);
            }

你可能感兴趣的:(Objective-C 中如何用数组和字典存储城市地区的代码)