Memory leak in NSString stringWithUTF8String

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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.

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!