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 經典字典數組排序的示例代碼,感謝年夜家對本站的支撐!
【Objective-C 經典字典數組排序 - 省郊區】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!