IOS UIPickView + sqlite select all cities in China, uipickviewsqlite

Source: Internet
Author: User

IOS UIPickView + sqlite select all cities in China, uipickviewsqlite
1. Case Description: by reading files, all Chinese cities are written into the sqlite database. Now UIPickView is used to select all Chinese cities, as shown below:
2. For the city object model, see http://blog.csdn.net/whzhaochao/article/details/42569145. The city model objects are as follows:

//// CityModel. h // readData /// Created by Zhao Chao on 14-8-28. // Copyright (c) 2014 Zhao Chao. all rights reserved. // # import <Foundation/Foundation. h> @ interface CityModel: NSObject @ property (nonatomic, copy) NSString * pid; // parent city ID @ property (nonatomic, copy) NSString * cityName; // city name @ property (nonatomic, copy) NSString * ids; // city ID @ end

3. For the sqlite operation BseDB class of the city database operation object, refer to Shanghai.
/// CityDB. h // readData /// Created by Zhao Chao on 14-8-28. // Copyright (c) 2014 Zhao Chao. all rights reserved. // # import "BaseDB. h "# import" CityModel. h "@ interface CityDB: BaseDB/*** CityDB Single Instance */+ (id) ShareDB;/*** create database * dbName: database name */-(void) creatTableWithDataBaseName :( NSString *) dbName;/*** Add a city * city: city * dbName: database name */-(BOOL) addCity :( CityModel *) city dbName :( NSString *) dbName;/*** select all cities * dbName: database name */-(id) selectAllCity :( NSString *) dbName;/*** select all provinces * dbName: database name */-(id) selectAllProvince :( NSString *) dbName;/*** delete all cities * dbName: database name */-(BOOL) deleteAllCity :( NSString *) dbName; /*** select a lower-level city through the upper-level province * city: upper-level city * dbName: database name */-(id) selectCityByProvince :( CityModel *) provice dbName :( NSString *) dbName; @ end
CityDB. m file implementation
/// CityDB. m // readData /// Created by Zhao Chao on 14-8-28. // Copyright (c) 2014 Zhao Chao. all rights reserved. // # import "CityDB. h "@ implementation CityDBstatic 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) selectAllCity :( NSString *) dbName {NSString * SQL = @ "select ids, cityName, pid from china "; return [self selectCity: SQL parmas: nil dbName: dbName];}-(id) selectCity :( NSString *) SQL parmas :( NSArray *) params dbName :( NSString *) dbName {NSArray * result = [self selectSql: SQL parmas: params dataBa SeName: 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];}-(BOOL) deleteAllCity :( NSString *) dbName {NSString * SQL = @ "delete from china "; return [self execSql: SQL parmas: nil dataBaseName: dbName] ;}@ end

4.city data processing: Chinese city data is stored in china.txt, which needs to be processed and written to the database. The following Code reads the file and loads the data into the database:
// Call the CitDB object to add a city to the database-(void) addCity :( CityModel *) city {[[CityDB ShareDB] addCity: city dbName: @ "China. sqlite "] ;}// Process City Data in china.txt and write it to the database-(void) readData {NSString * path = [[NSBundle mainBundle] pathForResource: @" china "ofType: @ "txt"]; NSLog (@ "% @", path); 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", ids, name, pid ); NSString * pids = [NSString stringwithuf8string: pid]; NSString * names = [NSString stringwithuf8string: name]; NSString * idss = [NSString stringwithuf8string: ids]; city. ids = idss; city. pid = pids; city. cityName = names; // insert a city to the database [self addCity: city]; NSLog (@ "% %%@% d", pids, names, idss, ++ I );}}


5. UIPickView displays the MainViewControoler user data. Its. h file content is as follows:
@ Interface MainViewController: UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> {CityModel * privceModel; // select the province CityModel * cityModel; // select the city CityModel * subCityModel; // select the prefecture-level city CityModel * areaModel; // select the UILabel * selectCity; // display the selected result} @ property (nonatomic, retain) NSArray * privices; // all provinces @ property (nonatomic, retain) NSArray * citys; // Save the corresponding city @ property (nonatomic, retain) NSArray * subCitys; // prefecture-level cities under the city @ property (nonatomic, retain) NSArray * area; // zone @ end

Add UIPickView to viewDidLoad of MainViewController and initialize data
-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. 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]; // initialize data 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]; city = [self. citys objectAtIndex: 0]; self. area = [[CityDB ShareDB] selectCityByProvince: city dbName: dataBaseName]; selectCity = [[UILabel alloc] initWithFrame: CGRectMake (0, 40,320, 30)];}

Implement the UIPickView's number of columns and number of rows proxy function. The number of columns is only four columns, and the number of rows in the first column is the number of provinces in China, so people return self. privices. count, but the second column must know the province selected in the first column, and then identify the city in the database through this province to know the number of rows to be displayed, the 3rd column is based on the number of rows selected from the 2nd column, and the 4th column is based on the number of columns selected from the 3rd column. The implementation code is as follows:
// UIPcikView a total of four columns-(NSInteger) numberOfComponentsInPickerView :( UIPickerView *) pickerView {return 4;} // load the number of rows per column-(NSInteger) pickerView :( UIPickerView *) pickerView numberOfRowsInComponent :( NSInteger) component {if (component = 0) {return self. privices. count;} else if (component = 1) {// obtain the province list in the first column: NSInteger privoceIndex = [pickerView selectedRowInComponent: 0]; CityModel * privoice = [self. privices objectAtIndex: privoceIndex]; // query from the database, city self under the province. citys = [[CityDB ShareDB] selectCityByProvince: privoice dbName: dataBaseName]; // return the number of cities 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 ;}else {return 0 ;}}
Load data in each column of each row for UIPickView. When obtaining data, make sure to determine whether it is empty.
// Get the name of each row in each column-(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 @ "";} else {CityModel * city = [self. subCitys objectAtIndex: row]; return city. cityName ;}} else if (component = 3) {if (self. area = nil) {return @ "";} else {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)]; // obtain the name lable. text = [self getCityName: row componet: component]; lable. font = [UIFont systemFontOfSize: 14]; return lable ;}
Finally, the selection response event of UIPickView is refreshed and the Pickview is displayed.
// Get the name of each row in each column-(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 @ "";} else {CityModel * city = [self. subCitys objectAtIndex: row]; return city. cityName ;}} else if (component = 3) {if (self. area = nil) {return @ "";} else {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)]; // obtain the name lable. text = [self getCityName: row componet: component]; lable. font = [UIFont systemFontOfSize: 14]; return lable ;}


Project complete engineering https://github.com/whzhaochao/IOSChinaCity





How to operate the sqlite3 database in ios

Use the Open Source library FMDB! Sqlite3 is encapsulated and easy to use!

In ios, how does sqlite and sqlserver remote database link? Interfaces are not required for data interaction,

I just came here to do the task.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.