时间:2020-11-26 22:57:22 | 栏目:iOS代码 | 点击:次
1.首先要准备好包含所有省市区的文档,将文档拖到我们建好的Xcode里
2.然后新建一个路径NSString *path = @" "; 再将省市区文档拖到@" "中;
3.在进行排序前,我们首先要先滤清思路:这答题的难题是在于如何将字典装入数组,再把数组装入字典,所以关键点就在于如何通过嵌套将每个字典与数组归到于它们相对应的数组与字典里 提供一个小思路:数组->字典->数组->字典->数组
4.完成上面的准备工作后,我们就可以开始进行省市区的排序了
根据路径产生相应的字符 tring *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 对字符串进行切割成为数组 NSArray *array = [str componentsSeparatedByString:@"\n"]; 建立一个大数组 NSMutableArray *mutableArray = [NSMutableArray array]; for (NSString *str in array) { 判断非空格字符,找出省 if (![str hasPrefix:@" "]) { 每找到一个省名字,就创建一个字典 NSMutableDictionary *proDic = [NSMutableDictionary dictionary]; 将省名存入字典,并设置Key为PROVIN [proDic setObject:str forKeyedSubscript:@"PROVIN"]; 创建一个数组,作为存下属市用 NSMutableArray *cityArray = [NSMutableArray array]; 将市数组存入字典,设置key位CITYARRAY [proDic setObject:cityArray forKeyedSubscript:@"CITYARRAY"]; [mutableArray addObject:proDic]; } 找到市名字 if ([str hasPrefix:@" "]&& ![str hasPrefix:@" "]) { 取出数组最后一个元素,代表市所隶属的省字典 NSDictionary *proDic = [mutableArray lastObject]; 将字典中预留的数组取出 NSMutableArray *cityArray = [proDic objectForKey:@"CITYARRAY"]; 每找到一个市,创建一个字典 NSMutableDictionary *cityDic = [NSMutableDictionary dictionary]; 将市名字存入字典 [cityDic setObject:str forKey:@"CITY"]; 给下属区域创建个数组作为预留 NSMutableArray *areaArray = [NSMutableArray array]; 存入字典 [cityDic setObject:areaArray forKey:@"AREAARRAY"]; 将市字典存入数组中 [cityArray addObject:cityDic]; } 找出下属区 if ([str hasPrefix:@" "]) { 找出隶属的省字典 NSDictionary *proDic = [mutableArray lastObject]; 找出市数组 NSMutableArray *cityArray = [proDic objectForKey:@"CITYARRAY"]; 找出存储市的字典 NSDictionary *cityDic = [cityArray lastObject]; 找出字典中区数区 NSMutableArray *areaArray = [cityDic objectForKey:@"AREAARRAY"]; 将区域名字存入数组 [areaArray addObject:str]; } } for (NSDictionary *dic in mutableArray) { NSLog(@"%@",[dic objectForKey:@"PROVIN"]); for (NSDictionary *cityDic in [dic objectForKey:@"CITYARRAY"]) { NSLog(@"%@",[cityDic objectForKey:@"CITY"]); for (NSString *string in [cityDic objectForKey:@"AREAARRAY"]) { NSLog(@"%@",string); } } }</span></span>
以上就是对Objective-C 经典字典数组排序的示例代码,谢谢大家对本站的支持!