我正在使用两种方法来r / w sqlite表:
+ (NSString *) getWeatherData:(int)rowID:(int)columnID {
NSString *savedWeatherData = [[NSString alloc] init];
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from TABLE where id=?";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
sqlite3_bind_int(selectstmt, 1, rowID);
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Weather *weatherObj = [[Weather alloc] initWithPrimaryKey:primaryKey];
weatherObj.weatherData = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, columnID)];
savedWeatherData = weatherObj.weatherData;
[weatherObj release];
}
}
}
return [savedWeatherData autorelease];
}
并保存一些数据:
+ (void) saveDataToDataBase:(NSString *)columnToUpdate:(int)rowID:(NSString *)value {
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
updateStmt = nil;
NSString *sqlString = [[@"update TABLE set " stringByAppendingString:columnToUpdate] stringByAppendingString:@"=? where id=?"];
const char *sql = [sqlString UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK) {
NSAssert1(0, @"Error while creating update statement. '%s'", sqlite3_errmsg(database));
} else { // select statement ok
sqlite3_bind_text(updateStmt, 1, [value UTF8String], -1, SQLITE_TRANSIENT); // replace first ? with value
sqlite3_bind_int(updateStmt, 2, rowID); // replace second ? with rowID
if(SQLITE_DONE != sqlite3_step(updateStmt)) {
NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(database));
} else {
// NSLog(@"Update completed !!!");
}
sqlite3_reset(updateStmt);
}
sqlite3_finalize(updateStmt);
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
使用Instruments,我发现sqlite的内存消耗非常大。 信息:在app启动期间,cca将100种不同类型的数据存储在DB中 - 对于每个数据,调用此saveDataToDataBase方法。 (如果没有互联网连接 - 将使用getWeatherData - 并且将再次读取cca 100种不同类型的数据)
请你能告诉我 - 是否可以优化内存消耗。
非常感谢!
亲切的问候!
答案 0 :(得分:0)
您需要确定selectstmt
。此外,您不应该在每次通话时打开和关闭数据库。保持对数据库的引用,只有当你真的不再需要它时才关闭它。 (第一种方法每次都不会关闭数据库。)
此外,您可以在打开数据库后设置缓存大小:
// Modify cache size so we don't overload memory. 50 * 1.5kb
if (sqlite3_exec(database, "PRAGMA CACHE_SIZE=50;", NULL, NULL, NULL) !
= SQLITE_OK) {
NSAssert1(0, @"Error: failed to set cache size with message '%s'.",
sqlite3_errmsg(database));
}