OC- 字典套数组 -- 省市区
OC- 字典套数组 -- 省市区
// 获取文件
NSString *str = [NSString stringWithContentsOfFile:@"area.txt" encoding:NSUTF8StringEncoding error:nil];
// 按\n截取
NSArray *line = [str componentsSeparatedByString:@"\n"];
// 新建空省数组
NSMutableArray *proArr = [NSMutableArray array];
//
for (NSString *lineStr in line) {
// 省
if (![lineStr hasPrefix:@" "]) {
// 新建市数组
NSMutableArray *citArr = [NSMutableArray array];
// 省字典
NSMutableDictionary *proDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:lineStr, @"provinceName", citArr, @"cit", nil];
[proArr addObject:proDic];
} else if (![lineStr hasPrefix:@" "]) {
// 市
// 新建区数组
NSMutableArray *areaArr = [NSMutableArray array];
// 新建市字典
NSMutableDictionary *citDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:lineStr, @"cityName", areaArr, @"area", nil];
// 获取市所属的省字典
NSMutableDictionary *proDic = proArr.lastObject;
// 获取市所属的市数组
NSMutableArray *citArr = [proDic objectForKey:@"cit"];
// 将建好的市子典添加到市数组中
[citArr addObject:citDic];
} else {
// 区
// 获取区所属的省字典
NSMutableDictionary *proDic = proArr.lastObject;
// 获取区所属的市数组
NSMutableArray *citArr = [proDic objectForKey:@"cit"];
// 获取区所属的市字典
NSMutableDictionary *citDic = citArr.lastObject;
// 获取区所属的区数组
NSMutableArray *areaArr = [citDic objectForKey:@"area"];
// 将区名直接添加到区数组中
[areaArr addObject:lineStr];
}
}
// 转换为控制台看见中文字符
NSData *data = [NSJSONSerialization dataWithJSONObject:proArr options:NSJSONWritingPrettyPrinted error:nil];
NSString *contentStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", contentStr);