tags:

views:

126

answers:

2

Hi,

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 whitespaceAndNewlineCharacterSet]];
 }

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

Thanks in advance.

A: 

This is because you are not releasing the previous str. Just release the str

[str release]

before the leak line.

taskinoor
str is autorelease in this code sample. Calling release on str will end in a double release.
Mecki
I assumed that str is retained somewhere else. Otherwise it is almost of no use as a instance member.
taskinoor
A: 

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).

Mecki