本文主要是介绍OC中用字典创建一个具有省市区的应用(简单的字典运用代码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
</pre><pre name="code" class="objc">#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) {// 准备工作NSString *path = @"/Users/dllo/Desktop/area.txt";// 根据路径产生相应的字符串NSString *str =[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];// 对字符串进行逐行切割NSArray *strArr = [str componentsSeparatedByString:@"\n"];// 创建一个省数组NSMutableArray *proArr = [NSMutableArray array];for (NSString *temp in strArr) {if (![temp hasPrefix:@" "]) {// 创建省字典NSMutableDictionary *proDic = [NSMutableDictionary dictionary];// 给省字典添加键值对// 省名[proDic setObject:temp forKey:@"proName"];// 创建一个市数组NSMutableArray *cityArr = [NSMutableArray array];// 把市数组作为第二对键值对添加到字典中[proDic setObject:cityArr forKey:@"cityArr"];// 把省字典放入到省数组中[proArr addObject:proDic];} else if([temp hasPrefix:@" " ] && ![temp hasPrefix:@" "]){// 找到对应城市// 创建市字典NSMutableDictionary *cityDic = [NSMutableDictionary dictionary];// 第一对键值对 市名[cityDic setObject:temp forKey:@"cityName"];// 第二队键值对 区数组NSMutableArray *zoneArr = [NSMutableArray array];[cityDic setObject:zoneArr forKey:@"zoneArr"];// 给市字典找一个位置// 先找到对应的省字典NSMutableDictionary *proDic = [proArr lastObject];// 然后再找对应的市数组NSMutableArray *cityArr = proDic[@"cityArr"];[cityArr addObject:cityDic];} else {// 先找省字典NSMutableDictionary *proDic = [proArr lastObject];// 市数组NSMutableArray *cityArr = proDic[@"cityArr"];// 市字典NSMutableDictionary *cityDic = [cityArr lastObject];// 区数组NSMutableArray *zoneArr = cityDic[@"zoneArr"];// 添加[zoneArr addObject:temp];}}// forin遍历省数组名for (NSMutableDictionary *dic in proArr) {NSLog(@"------------------");NSLog(@"%@",dic[@"proName"]);NSLog(@"------------------");NSMutableArray *cityArr = dic[@"cityArr"];for (NSMutableDictionary *cityDic in cityArr) {NSLog(@"%@",cityDic[@"cityName"]);NSLog(@"***************");NSMutableArray *zoneArr = cityDic[@"zoneArr"];for (NSString *str in zoneArr) {NSLog(@"%@",str);NSLog(@"***************");}}}return 0;
}
代码中已给出详细注释
这篇关于OC中用字典创建一个具有省市区的应用(简单的字典运用代码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!