Search code examples
iosxcodememory-leaksuisearchdisplaycontroller

UISearchDisplayController memory leaks stack up when typing


I recently started learning objective-C and cocoa. I'm slowly starting to learn about memory management. Usually i kinda grasp the logic of it. But right now i'm kinda confused. Here's my problem:

I am trying to make a simple ios app with search function. I have a UISearchDisplayController with a UISearchbar inside a UITableViewController that leaks (instruments..) like hell when I type something in it. Compiler and Analyzer both show no warnings or errors. Just instruments.

I get the error from this line inside the handleSearchTerm method:

self.searchResults = [[datenSort filteredArrayUsingPredicate:predicate] mutableCopy];

Here's my handleSearchTerm method:

- (void)handleSearchForTerm:(NSString *)searchTerm
{   
    self.savedSearchTerm = searchTerm;
    if ([self searchResults] == nil)
    {    

       NSMutableArray *array = [[NSMutableArray alloc] init];       
       self.searchResults = array;
       [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];
    if ([[self savedSearchTerm] length] != 0)
    {

       NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Name contains[cd] %@)", searchTerm];
       self.searchResults = [[datenSort filteredArrayUsingPredicate:predicate] mutableCopy];

      }


}

the properties are all released in the dealloc method. and they are:

@property (nonatomic, copy) NSString *savedSearchTerm;
@property (nonatomic, retain) NSMutableArray *datenSort;
@property (nonatomic, retain) NSMutableArray *searchResults;

and this is how i put them inside tableview:cellForRowAtIndexPath:

    if(tableView == self.searchDisplayController.searchResultsTableView){

        dataItem = [searchResults objectAtIndex:indexPath.row];

    }else {

        dataItem = [datenSort objectAtIndex:indexPath.row];

    }

your answers are VERY much appreciated!


Solution

  • This line leaks:

    self.searchResults = [[datenSort filteredArrayUsingPredicate:predicate] mutableCopy];
    

    According to the Memory Management rules, you own any object you create and you create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy".

    Therefore, mutableCopy returns a retained object and the searchResults property setter also retains the object, resulting in the object being over-retained. The solution is to relinquish ownership of the object by sending it a release...

    NSArray *temp = [[datenSort filteredArrayUsingPredicate:predicate] mutableCopy];
    self.searchResults = temp;
    [temp release];
    

    ...or autorelease message.

    self.searchResults = [[[datenSort filteredArrayUsingPredicate:predicate] mutableCopy] autorelease];