本案例先將中國所有城市資料寫入 SQLite 資料庫,再透過 UIPickerView 實現省、市、區的三級聯動選擇。效果圖如下:
// CityModel.h #import <Foundation/Foundation.h> @interface CityModel : NSObject @property (nonatomic, copy) NSString *pid; // 父級城市ID @property (nonatomic, copy) NSString *cityName; // 城市名 @property (nonatomic, copy) NSString *ids; // 城市ID @end
在封裝好的 BaseDB 基礎上,進一步封裝城市相關的資料庫操作。
// CityDB.h #import "BaseDB.h" #import "CityModel.h" @interface CityDB : BaseDB +(id)ShareDB; -(void)creatTableWithDataBaseName:(NSString *)dbName; -(BOOL)addCity:(CityModel *)city dbName:(NSString *)dbName; -(id)selectAllCity:(NSString *)dbName; -(id)selectAllProvince:(NSString *)dbName; -(BOOL)deleteAllCity:(NSString *)dbName; -(id)selectCityByProvince:(CityModel *)provice dbName:(NSString *)dbName; @end
// CityDB.m
#import "CityDB.h"
@implementation CityDB
static CityDB *citydb;
+(id)ShareDB {
if (citydb == nil) {
citydb = [[CityDB alloc] init];
}
return citydb;
}
-(void)creatTableWithDataBaseName:(NSString *)dbName {
NSString *sql = @"create table china (ids text primary key, cityName text, pid text)";
[self createTable:sql dataBaseName:dbName];
}
-(BOOL)addCity:(CityModel *)city dbName:(NSString *)dbName {
NSString *sql = @"insert into china values (?,?,?)";
NSArray *params = @[city.ids, city.cityName, city.pid];
return [self execSql:sql parmas:params dataBaseName:dbName];
}
-(id)selectCity:(NSString *)sql parmas:(NSArray *)params dbName:(NSString *)dbName {
NSArray *result = [self selectSql:sql parmas:params dataBaseName:dbName];
NSMutableArray *citys = [NSMutableArray array];
for (NSDictionary *dic in result) {
CityModel *city = [[CityModel alloc] init];
city.ids = [dic objectForKey:@"ids"];
city.cityName = [dic objectForKey:@"cityName"];
city.pid = [dic objectForKey:@"pid"];
[citys addObject:city];
}
return citys;
}
-(id)selectAllProvince:(NSString *)dbName {
NSString *sql = @"select ids, cityName, pid from china where pid = ?";
NSArray *parmas = @[@"0"];
return [self selectCity:sql parmas:parmas dbName:dbName];
}
-(id)selectCityByProvince:(CityModel *)provice dbName:(NSString *)dbName {
NSString *sql = @"select * from china where pid = ?";
NSArray *params = @[provice.ids];
return [self selectCity:sql parmas:params dbName:dbName];
}
@end
城市資料放在 china.txt 中,需讀檔後逐筆寫入資料庫:
-(void)addCity:(CityModel *)city {
[[CityDB ShareDB] addCity:city dbName:@"China.sqlite"];
}
-(void)readData {
NSString *path = [[NSBundle mainBundle] pathForResource:@"china" ofType:@"txt"];
char pid[30], name[30], ids[30];
FILE *f = fopen([path UTF8String], "r");
int i = 0;
while (!feof(f)) {
CityModel *city = [[CityModel alloc] init];
fscanf(f, "%s %s %s", ids, name, pid);
city.ids = [NSString stringWithUTF8String:ids];
city.cityName = [NSString stringWithUTF8String:name];
city.pid = [NSString stringWithUTF8String:pid];
[self addCity:city];
NSLog(@"%@ %@ %@ %d", city.pid, city.cityName, city.ids, ++i);
}
}

MainViewController 負責資料顯示,宣告四個模型分別對應省、市、地級市、區,並用四個陣列保存各級資料。
@interface MainViewController : UIViewController{ CityModel *privceModel; // 選擇的省 CityModel *cityModel; // 選擇的市 CityModel *subCityModel; // 選擇的地級市 CityModel *areaModel; // 選擇的區 UILabel *selectCity; // 顯示選擇的結果 } @property (nonatomic, retain) NSArray *privices; // 所有省份 @property (nonatomic, retain) NSArray *citys; // 省下對應的市 @property (nonatomic, retain) NSArray *subCitys; // 市下對應的地級市 @property (nonatomic, retain) NSArray *area; // 區 @end
在 viewDidLoad 中加入 UIPickerView 並初始化資料:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
UIPickerView *pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 100, 0, 0)];
pickView.dataSource = self;
pickView.delegate = self;
pickView.showsSelectionIndicator = YES;
pickView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:pickView];
// 初始化資料
self.privices = [[CityDB ShareDB] selectAllProvince:dataBaseName];
CityModel *city = [self.privices objectAtIndex:0];
self.citys = [[CityDB ShareDB] selectCityByProvince:city dbName:dataBaseName];
city = [self.citys objectAtIndex:0];
self.subCitys = [[CityDB ShareDB] selectCityByProvince:city dbName:dataBaseName];
selectCity = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 320, 30)];
}
實現列數與行數的代理方法。關鍵在於:第二列的行數取決於第一列選中的省份,第三列取決於第二列,第四列取決於第三列,逐級從資料庫查詢:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 4;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0) {
return self.privices.count;
} else if (component == 1) {
NSInteger privoceIndex = [pickerView selectedRowInComponent:0];
CityModel *privoice = [self.privices objectAtIndex:privoceIndex];
self.citys = [[CityDB ShareDB] selectCityByProvince:privoice dbName:dataBaseName];
return self.citys.count;
} else if (component == 2) {
NSInteger cityIndex = [pickerView selectedRowInComponent:1];
if (self.citys.count == 0) { return 0; }
CityModel *subCitys = [self.citys objectAtIndex:cityIndex];
self.subCitys = [[CityDB ShareDB] selectCityByProvince:subCitys dbName:dataBaseName];
return self.subCitys.count;
} else if (component == 3) {
NSInteger subCityIndex = [pickerView selectedRowInComponent:2];
if (self.subCitys.count == 0) { return 0; }
CityModel *ares = [self.subCitys objectAtIndex:subCityIndex];
self.area = [[CityDB ShareDB] selectCityByProvince:ares dbName:dataBaseName];
return self.area.count;
}
return 0;
}
為每列每行載入名稱時,務必判斷是否為空,避免越界:
-(NSString *)getCityName:(NSInteger)row componet:(NSInteger)component {
if (component == 0) {
CityModel *city = [self.privices objectAtIndex:row];
return city.cityName;
} else if (component == 1) {
CityModel *city = [self.citys objectAtIndex:row];
return city.cityName;
} else if (component == 2) {
if (self.subCitys == nil) { return @""; }
CityModel *city = [self.subCitys objectAtIndex:row];
return city.cityName;
} else if (component == 3) {
if (self.area == nil) { return @""; }
CityModel *city = [self.area objectAtIndex:row];
return city.cityName;
}
return @"";
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
lable.text = [self getCityName:row componet:component];
lable.font = [UIFont systemFontOfSize:14];
return lable;
}
最後在選擇回呼中刷新 UIPickerView 並顯示結果。透過 SQLite 持久化儲存城市資料,再搭配 UIPickerView 的逐級聯動查詢,即可實現流暢的全國城市選擇體驗。