【问题标题】:How to solve Memory leaks for following Sqlite code?如何解决以下 Sqlite 代码的内存泄漏?
【发布时间】:2011-09-28 01:44:54
【问题描述】:

我在以下 Sqlite 代码中的 Instruments 中出现内存泄漏。

NSArray *result = [self executeQuery:sql arguments:argsArray];

它调用以下方法。

- (NSArray *)executeQuery:(NSString *)sql arguments:(NSArray *)args {
sqlite3_stmt *sqlStmt;

if (![self prepareSql:sql inStatament:(&sqlStmt)])
    return nil;

int i = 0;
int queryParamCount = sqlite3_bind_parameter_count(sqlStmt);
while (i++ < queryParamCount)
    [self bindObject:[args objectAtIndex:(i - 1)] toColumn:i inStatament:sqlStmt];

NSMutableArray *arrayList = [[NSMutableArray alloc] init];
int columnCount = sqlite3_column_count(sqlStmt);
while ([self hasData:sqlStmt]) {
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    for (i = 0; i < columnCount; ++i) {
        id columnName = [self columnName:sqlStmt columnIndex:i];
        id columnData = [self columnData:sqlStmt columnIndex:i];
        [dictionary setObject:columnData forKey:columnName];
    }
    [arrayList addObject:[dictionary autorelease]];
}

sqlite3_finalize(sqlStmt);

return arrayList;
}

我该如何解决?

【问题讨论】:

    标签: iphone objective-c ios4 memory-leaks instruments


    【解决方案1】:

    我们需要查看您的 executeQuery 方法的代码 - 它应该返回一个自动发布的结果,但也许不是。

    你可以试试;

    NSArray *result = [[self executeQuery:sql arguments:argsArray] autorelease];
    

    但我会警惕盲目地尝试而没有真正了解 executeQuery 的详细操作。

    编辑:

    好的,这是你的问题;

    NSMutableArray *arrayList = [[NSMutableArray alloc] init];
    

    要么将其创建为自动释放的数组,要么使用以下方法完成方法;

    return [arrayList autorelease];
    

    【讨论】:

    • 编辑了我的问题。 executeQuery 详情。
    • 查看更新的答案。显然,这可能会产生后果,具体取决于您的其余代码如何使用 executeQuery 结果,但如果您与内存管理保持一致,您会没事的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多