gpt4 book ai didi

objective-c - 使用sqlite的内存泄漏

转载 作者:搜寻专家 更新时间:2023-10-30 20:04:13 27 4
gpt4 key购买 nike

对于这些行,我在 Instruments 上收到内存泄漏警告:

 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;
}

我想在 View 中显示一个空字符串而不是“nil”,所以我首先将年份设置为一个空字符串。有一个更好的方法吗?我该如何解决这个漏洞?

感谢您的帮助!

最佳答案

在 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
}

关于objective-c - 使用sqlite的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726885/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com