开发者

Getting leak at stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]

I am getting leak at below code:

search.h

NSString *str;

search.m

-(void)searchMethod:(UISearchBar *)aSearchBar
{
     /*******Showing leak at below line *************/
     str=[aSearchBar.text stringByTrimmingCharactersInSet:
                   [NSCharacterSet whitespaceAndNewlineCharac开发者_JAVA百科terSet]];
 }

I am not getting how to solve this can any one help me to solve this.

Thanks in advance.


How do you know this is a leak? str is autorelease in your example, that means it will release itself some time after this method returned. Only if you would perform this task on a separate thread with no autorelease pool in place or with an auto release pool you never clear, str could leak. If this code runs on main thread, str will for sure not leak.

I rather think you get a crash because you don't retain str. You store str into a global variable, but without increasing the retain count. That means once str is autoreleased, your grobal variable points to invalid memory. To make sure an object stays alive beyond the scope of a method, you must retain it (unless you created this object via alloc/init..., new... or copy...).

str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method

Of course if you keep an object alive like this, you must release it yourself somewhere in your code. So if you want this variable to be overridden each time the method is called, use

[str release];
str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method

Don't forget to also release str within the dealloc method of this object (override dealloc for that; don't forget to call [super dealloc] within the overridden method as last instruction).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜