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 經典字典數組排序的示例代碼,謝謝大家對本站的支持!