标签: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;
}标签:style blog http io ar os 使用 sp for
原文地址:http://blog.csdn.net/arbboter/article/details/41874751