我的应用程序有一个 SQLite 数据库。要从数据库中检索实体,我使用以下方法:
- (sqlite3*) openDatabaseNamed:(NSString*)databaseName
{
if(![databaseName isEqualToString:kTopInternationalDatabaseName] &&
![databaseName isEqualToString:kTop500RODatabaseName]){
NSAssert(nil, @"Database does not exist!");
}
sqlite3 * dataBase;
NSString * path;
path = [[NSBundle mainBundle] pathForResource:databaseName ofType:@"sqlite3"];
if (sqlite3_open([path UTF8String], &dataBase) != SQLITE_OK) {
NSString * errorString = [NSString stringWithFormat:@"[SQLITE] Unable to open database <%@> ",databaseName];
NSAssert(nil,errorString);
}
return dataBase;
}
- (NSArray *) getAllEntitiesForDatabaseNamed:(NSString*)databaseName
{
(...)
sqlite3 * database = [self openDatabaseNamed:databaseName];
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@",databaseName];
NSArray *properties = [entityClass classProperties];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)
== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
for (int i=2; i<countLimit; i++){
chars = (char *) sqlite3_column_text(statement,i+1);
if(chars != NULL)
{
containerString = [NSString stringWithUTF8String:chars];
if(containerString && containerString.length>0){
[entityModel setValue:containerString forKey:properties[i]];
}
}
}
[retval addObject:entityModel];
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return retval.copy;
}
一切都按预期工作。为了将实体的自定义字段设置为数据库中的特定值,我使用以下方法:
- (void)setEntity:(EntityModel *)entity favorite:(BOOL)favorite
{
NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET favorite = %i WHERE position = '%i';",kDatabaseName,favorite?1:0,entity.positionInTop];
sqlite3_stmt *statement;
sqlite3 * database = [self openDatabaseNamed:kTop500RODatabaseName];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)
== SQLITE_OK) {
sqlite3_step(statement);
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
正在发生的事情有点奇怪。如果我使用更新方法并在应用程序查询的同一生命周期中使用getAllEntitiesForDatabaseNamed
我所做的更改 来查询所有实体setEntity:Favorite:
。另一方面,如果我使用更新方法,然后关闭应用程序并重新启动它,我所做的更改就会setEntity:Favorite:
丢失。知道为什么会这样吗?
PS:我也试过使用sqlite3_exec
,结果还是一样:
if (sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL) != SQLITE_OK) {
// deal with error...
NSLog(@" -- ERROR!");
}