標籤:style blog http io ar os 使用 sp for
概要
本章主要簡示了IOS開發中使用sqlite來持久化資料,其使用方法和C++中使用sqlite基本一致。
結果展示
(其實沒啥看的)
流程概要
1.因為使用的是以前的工程,所以主需要再拖拉兩個按鈕就差不多了
2.因為要使用sqlite,所以需要引用sqlite庫(sqlite架構),在工程設定裡面的,如所示
3.在原先的序列化類別裡面添加儲存和載入資料到資料庫的函數,即可,具體見代碼。
主要代碼
資料庫作業碼
-(id)initWithFilePath:(NSString*)file{ self = [super init]; if(self) { // 開啟資料庫,建立表 sqlite3_open([file UTF8String], &_sqlite); NSString* cmd = [NSString stringWithFormat:@"CREATE TABLE staff(nickName TEXT, email TEXT PRIMARY KEY, phone TEXT, sex TEXT, 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 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) { // 第一行為欄位名 // 第二行才是資料 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;}
工程代碼(略)
IOS開發-資料持久化(二)【sqlite資料庫】