IOS Uipickview+sqlite Select all city cases in China

Source: Internet
Author: User

1. Case briefBy reading the file, all cities in China are written to the SQLite database and are now available through Uipickview for all cities in China, as shown below
2. City object model All city data of China see http://blog.csdn.net/whzhaochao/article/details/37969145, City Model objects are as follows
  citymodel.h//  readdata////  Created by Carrie on 14-8-28.//  Copyright (c) 2014 Carrie. 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. City database Operation Object SQLite sealed Operation Bsedb class see http://blog.csdn.net/whzhaochao/article/details/38865535, and then encapsulate the database Operation object CityDBCityDB.h file for the city object
  citydb.h//  readdata////  Created by Carrie on 14-8-28.//  Copyright (c) 2014 Carrie. All rights reserved.//#import "BaseDB.h" #import "CityModel.h" @interface citydb:basedb/** *citydb single case */+ (ID) sharedb;/** * CREATE DATABASE * dbName: Database name */-(void) Creattablewithdatabasename: (nsstring*) dbname;/** * Add a city * cities: City * DbName: Database name */-(BO OL) 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) Dele Teallcity: (nsstring*) dbname;/** * Select a sub-city from the previous province * Cities: Previous City * dbName: Database name */-(ID) selectcitybyprovince: (citymodel*) Provice dbName: (nsstring*) dbName; @end
CITYDB.M File Implementation
citydb.m//readdata////Created by Carrie on 14-8-28.//Copyright (c) 2014 Carrie.        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 *[email protected] "CREATE TABLE China (IDs text PR    Imary key,cityname text,pid text) "; [Self Createtable:sql databasename:dbname];} -(BOOL) addcity: (Citymodel *) City DbName: (NSString *) dbname{nsstring *[email protected] "INSERT into China values (    ?,?,?)";    Nsarray *[email protected][city.ids,city.cityname,city.pid]; return [self execsql:sql parmas:params databasename:dbname];}    -(ID) selectallcity: (NSString *) dbname{nsstring *[email protected] "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 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 *[email protected] "Select Ids,cityname,pid from the China where P    Id=? ";    Nsarray *[email protected][@ "0"]; return [self selectcity:sql parmas:parmas dbname:dbname];} -(ID) selectcitybyprovince: (Citymodel *) provice dbName: (NSString *) dbname{nsstring *[email protected] "SELECT *    From the China where pid=? ";    Nsarray *[email protected][provice.ids]; return [self selectcity:sql parmas:params dbname:dbname];}    -(BOOL) deleteallcity: (NSString *) dbname{nsstring *[email protected] "Delete from China"; return [Self execsql:sqL Parmas:nil Databasename:dbname];} @end

4. Urban data processingChinese city data are placed in china.txt, which need to be processed and written to the database, read the file loaded data to write to the database code as follows
Call the Citdb object to add a city-(void) addcity to the database: (citymodel*) city{    [[Citydb sharedb] addcity:city dbname:@ "China.sqlite"] ;} Processing China.txt City data, writing 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%s%s", ids,name,pid);        NSString *pids=[nsstring Stringwithutf8string:pid];        NSString *names=[nsstring Stringwithutf8string:name];        NSString *idss=[nsstring Stringwithutf8string:ids];        CITY.IDS=IDSS;        City.pid=pids;        City.cityname=names;        Insert a city into the database        [self addcity:city];        NSLog (@ "%@%@%@%d", pids,names,idss,++i);}            }


5.UIPickView Display DataMainviewcontrooler the display of user data, the contents of the. h file are as follows
@interface mainviewcontroller:uiviewcontroller<uipickerviewdatasource,uipickerviewdelegate>{    Citymodel *privcemodel;     The selected province    Citymodel *citymodel;       The selected city    Citymodel *subcitymodel;    Selected prefecture-level    Citymodel *areamodel;       The selected area    UILabel *selectcity;        Show selected results} @property (Nonatomic,retain) Nsarray *privices;    All provinces @property (nonatomic,retain) Nsarray *citys;       Save the corresponding City @property (nonatomic,retain) Nsarray *subcitys;    City-level @property (Nonatomic,retain) Nsarray *area;        District @end

Add Uipickview and initialize data in Mainviewcontroller's Viewdidload
-(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, +, +)];} 

To implement Uipickview, the number of columns and the number of row agent functions, the column count is only 4 columns, The number of rows in the first column is the number of provinces in China so it's OK to return to Self.privices.count, but the second column needs to know which province the first column is selected, and then use the province to isolate the following city from the database to know the number of rows to display, the 3rd column is based on the number of rows selected in the 2nd column , the implementation code is as follows:
Uipcikview Total 4 Columns-(Nsinteger) Numberofcomponentsinpickerview: (Uipickerview *) pickerview{return 4;} Load rows per column-(Nsinteger) Pickerview: (Uipickerview *) Pickerview numberofrowsincomponent: (Nsinteger) component{if (compo    nent==0) {return self.privices.count;        }else if (component==1) {//Get the first column selected list of provinces Nsinteger Privoceindex=[pickerview selectedrowincomponent:0];        Citymodel *privoice=[self.privices Objectatindex:privoceindex];        Query from the database, the province below the city Self.citys=[[citydb Sharedb] Selectcitybyprovince:privoice dbname:databasename];     Return the number of the city 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 the data for each row per column for Uipickview, and be aware of whether it is empty when getting data
Gets the name of each row of 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)]; Get name Lable.text=[self Getcityname:roW Componet:component];        Lable.font=[uifont systemfontofsize:14]; return lable;}
Finally implement the Uipickview selection response event Refresh Pickview and display the selected results
Gets the name of each row of 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)]; Get name Lable.text=[self Getcityname:roW Componet:component];        Lable.font=[uifont systemfontofsize:14]; return lable;}


Project Complete Engineering http://download.csdn.net/detail/whzhaochao/7837681




IOS Uipickview+sqlite Select all city cases in China

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.