打开sqlite数据库时内存泄漏

时间:2011-07-03 10:16:37

标签: objective-c sqlite

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

- (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");  
    }   
}

1 个答案:

答案 0 :(得分:2)

您正在泄露,因为您没有致电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");  
}