【发布时间】:2011-12-07 10:27:02
【问题描述】:
我花了几个小时试图解决这个问题,但我刚刚放弃了;我不知道出了什么问题。
在我的应用程序中,我执行嵌套 SQL 操作来正确设置我的所有对象。由于某种原因,有时 sqlite3 对象无法正确释放,导致内存飙升。我知道正确使用 sql3_close 和 sql3_finalize 是一个问题。但是,正如您将看到的,我认为我正确地使用了它们。
这是问题的根源:
- (NSArray *) getAllSessions {
if (sqlite3_open(dbPath, &db) == SQLITE_OK) {
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
//I found out that doing something like that
//toAdd.in_loc = [self getIndoorLocationWithId:[NSNumber numberWithInt:(int)sqlite3_column_int(statement, 6)]];
//messes the memory up all the time
//but doing that works OK:
NSNumber *_id = [[NSNumber alloc] initWithInt:(int) sqlite3_column_int(statement, 5)];
toAdd.out_loc = [self getOutdoorLocationWithId:_id];
[_id release];
//So I did the same with the second one, but this one messes memory up:
NSNumber *id2 = [[NSNumber alloc] initWithInt:(int)sqlite3_column_int(statement, 6)];
toAdd.in_loc = [self getIndoorLocationWithId:id2];
[id2 release];
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
所以这里是搞乱记忆的一个:
- (IndoorLocation *) getIndoorLocationWithId:(NSNumber *) locId {
if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK) {
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
//if I comment the thing below it works
NSNumber *_id = [[NSNumber alloc] initWithInt:(int) sqlite3_column_int(statement, 5)];
toReturn.outLoc = [self getOutdoorLocationWithId:_id];
[_id release];
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
所以在搞乱内存的那个中,我使用了与第一次完全相同的函数(getOutdoorLocationwithId),以同样的方式但它不起作用,sqlite3 对象没有被正确释放。
我希望你能理解我的问题,这让我发疯了!
【问题讨论】:
-
数据库已经在 getAllSessions 中打开,重新打开然后关闭会搞砸。然后在这两种方法中声明一个返回类型,但你没有返回任何东西。 xcode 不会抱怨这个吗?
-
为了简单起见,我没有包含所有代码。关于您的第一点,我同意,但为什么它第一次有效,第二次无效?
标签: ios memory memory-management sqlite