Memory leak in NSString stringWithUTF8String

2019-01-20 03:21发布

I am making a call to a database. After my call, I've found leaks in NSString. Anybody have a solution to remove it?

 NSString *pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 5)];

In above code, I found 90% leaks. I just read data from database.

2条回答
贼婆χ
2楼-- · 2019-01-20 03:40

please explain the question well else others can't identify your exact problem.

I think you are you are assigning the value of [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 5)]; to your class object property.

You can release the assigned class string property in the corresponding class dealloc method.Also set it nil.

Example:

if you are doing

YourClass *classObj =[ YourClass  alloc] init];

classObj.myStringvariable = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 5)];

the class structure will like

@interface YourClass {

    NSString *myStringvariable ;

}

@property (nonatomic,retain)  NSString *myStringvariable ;

.m file will be

@synthesise myStringvariable ;


-(void)init{

 myStringvariable  = @"";

}

-(void)dealloc{

 [myStringvariable  release];
 myStringvariable  = nil;
}

Check it.. this structure will not show memory leak.

查看更多
时光不老,我们不散
3楼-- · 2019-01-20 03:43

Are you calling sqlite3_finalize() to free up memory?

If you are doing it, then the leak is possibly with the NSString, but we would need to know what you do with it (it is autoreleased, so you don't need to release it, but you could be retaining it somewhere else in your code).

Furthermore, it is not safe to pass sqlite3_column_text directly into stringWithUTF8String, since in case it returns nil, your application will crash.

You might also consider using fMDB, an ObjC wrapper around sqlite3. Find it here.

查看更多
登录 后发表回答