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

标签 objective-c sqlite

当我在 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/

相关文章:

ios - 方法没有被调用但在我构建时没有错误

iOS:从照片库打开图像

ios - 从不适用于 prepareForSegue 的原型(prototype)单元传输 NSString

ios - 无法从另一个 ViewController 调用方法

sql - 具有反向 LIKE 条件的查询

Android:在 SQLite 数据库上写入多线程

objective-c - 添加代码以动态阻止

sql - 使用LIKE命令%pattern%从sqlite数据库获取数据,但'%'+ pattern'%'无效

python - 我需要 sqlite3 的提示

sql - 在sqlite中查找最长的条纹