Overview
This chapter is a brief illustration of the use of SQLite to persist data in iOS development, using a method that is basically consistent with the use of SQLite in C + +.
results show
(actually nothing to see)
Process Overview
1. Because the use of the previous project, so the main need to drag two more buttons, almost.
2. Because you want to use SQLite, you need to refer to the SQLite Library (SQLite framework), in the project settings, as shown in
3. In the original serialization class, add the function to save and load the data to the database, you can see the code in detail.
Main code
Database Operation code
-(ID) Initwithfilepath: (nsstring*) file{self = [super init]; if (self) {//Open database, CREATE table Sqlite3_open ([File utf8string], &_sqlite); nsstring* cmd = [nsstring stringwithformat:@ "CREATE TABLE staff (nickname text, email text PRIMARY KEY, phone text, sex TEX T, Position TEXT) "]; Sqlite3_exec (_sqlite, [cmd utf8string], NULL, NULL, NULL); } return self;} -(void) sqlitesave{nsstring* cmd = [nsstring stringwithformat:@ "INSERT into OR replacestaff VALUES ('%@ ', '%@ ', '%@ ', '%@ ', '%@ '); ", Self._nickname, Self._email, Self._phone, Self._sex, self._position]; Sqlite3_exec (_sqlite, [cmd utf8string], NULL, NULL, NULL);} -(void) sqliteload{nsstring* cmd = [NSString stringwithformat:@ "SELECT * from the staff;"]; int nrow = 0; int ncol = 0; char** PResult = NULL; int nret = 0; Nret = sqlite3_get_table (_sqlite, [cmd utf8string], &presult, &nrow, &ncol, NULL); if (nret = = Sqlite_ok && Ncol = = 5) { First behavior field name//second row is the data int i = Ncol; Self._nickname = [NSString stringwithformat:@ "%s", presult[i++]]; Self._email = [NSString stringwithformat:@ "%s", presult[i++]]; Self._phone = [NSString stringwithformat:@ "%s", presult[i++]]; Self._sex = [NSString stringwithformat:@ "%s", presult[i++]]; Self._position = [NSString stringwithformat:@ "%s", presult[i++]]; }}-(void) Encodewithcoder: (Nscoder *) acoder{[acoder encodeobject:self._nickname forkey:@ "nickname"]; [Acoder encodeobject:self._email forkey:@ "email"]; [Acoder encodeobject:self._phone forkey:@ "Phone"]; [Acoder encodeobject:self._sex forkey:@ "Sex"]; [Acoder encodeobject:self._position forkey:@ "position"];} -(ID) Initwithcoder: (Nscoder *) adecoder{self._nickname = [Adecoder decodeobjectforkey:@ "nickname"]; Self._email = [Adecoder decodeobjectforkey:@ "email"]; Self._phone = [Adecoder decodeobjectforkey:@ "Phone"]; Self._sex = [Adecoder decodeobjectforkey:@]Sex "]; Self._position = [Adecoder decodeobjectforkey:@ "position"]; return self;}
Engineering Code (slightly)
iOS Development-Data Persistence (ii) "SQLite database"