gpt4 book ai didi

objective-c - 打开sqlite数据库时内存泄漏

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

当我在 Instruments openDatabase 方法上运行导致泄漏时,从 didFinishLaunchingWithOptions 调用了以下方法。请建议我如何清除

- (NSString*)getdestinationPath {
NSArray *pathsArray=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath=[doumentDirectoryPath stringByAppendingPathComponent:dataBaseName];
NSLog(@"database path %@",destinationPath);
return destinationPath;
}




- (void)chkAndCreateDatbase {
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSString *destinationPath=[self getdestinationPath];
if ([fileManger fileExistsAtPath:destinationPath]){
//NSLog(@"database localtion %@",destinationPath);
return;
}
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:dataBaseName];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}





- (void)openDatabase {
path=[self getdestinationPath];
if (sqlite3_open([path UTF8String], &database)==SQLITE_OK) // here leak is showing
{
NSLog(@"dataBaseOpen");
}
else {
sqlite3_close(database);
NSLog(@"dataBaseNotOpen");
}
}

最佳答案

你正在泄漏,因为你没有调用 sqlite3_close(database) 当你得到 SQLITE_OK 时。

if (sqlite3_open([path UTF8String], &database)==SQLITE_OK) 
{
NSLog(@"dataBaseOpen");
// leak happens here, do stuff then call sqlite3_close(database), or move it out of the if/else block.

}
else {
sqlite3_close(database);
NSLog(@"dataBaseNotOpen");
}

关于objective-c - 打开sqlite数据库时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562281/

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