内存泄漏使用sqlite

时间:2011-01-18 17:11:28

标签: objective-c memory-leaks sqlite

我在这些线路的仪器上收到内存泄漏警告:

 NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

 year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];

以下是此部分的代码:

-(NSMutableArray *)selectUsersList:(NSString *)condition:(NSString *)sort
{
    NSMutableArray *users = [[NSMutableArray alloc] init];

    if (sqlite3_open([self.databasePath UTF8String], &database) != SQLITE_OK)
    {
      sqlite3_close(database);
      NSAssert(0, @"Failed to open database");
    }
    else 
    {
      NSString *query = @"SELECT * FROM users";
      if (condition != nil)
      {
        NSString *newQuery = [NSString stringWithFormat:@"%@ %@", query, condition];
        query = newQuery;
      }
      if (sort != nil) {
        NSString *newsort = [NSString stringWithFormat:@"%@ %@", query, sort];
        query = newsort;
      }
      sqlite3_stmt *statement;

      if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            }
            NSString *year= @"";
            if (sqlite3_column_text(statement, 2) != nil)
            {
                year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            }

            User *user = [[User alloc] initWithName:name year:year];

            [users addObject:user]; 
            [user release];             
        }
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
  }
  return users;
}

我想在视图上显示一个空字符串而不是'nil',所以我先将year设置为空字符串。有一个更好的方法吗?我该如何解决这个漏洞?

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

在while循环之后,必须使用sqlite3_finalize()清除sqlite3语句的内存。所以:

if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

        NSString *year= @"";
        if (sqlite3_column_text(statement, 1) != nil) {
            year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
        }

        User *user = [[User alloc] initWithName:name year:year];
        [users addObject:user]; 
        [user release];   
    }
    sqlite3_finalize(statement); // DO THIS
}