开发者

UITableView and SearchBar problem

I'm trying to add a Search bar to my UITableView. I followed this tutorial: http://clingingtoideas.blogspot.com/2010/02/uitableview-how-开发者_如何转开发to-part-2-search.html.

I'm getting this error if I type a letter in the search box: Rooster(10787,0xa05ed4e0) malloc: *** error for object 0x3b5f160: double free *** set a breakpoint in malloc_error_break to debug.

This error occurs here:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self handleSearchForTerm:searchString];

    return YES;
}

(on the second line)

- (void)handleSearchForTerm:(NSString *)searchTerm {
    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release];
    }

    //Empty the searchResults array
    [[self searchResults] removeAllObjects];

    //Check if the searchTerm doesn't equal zero...
    if ([[self savedSearchTerm] length] != 0) {
        //Search the whole tableList (datasource)
        for (NSString *currentString in tableList) {
            NSString *klasString = [[NSString alloc] init];
            NSInteger i = [[leerlingNaarKlasList objectAtIndex:[tableList indexOfObject:currentString]] integerValue];
            if(i != -1) {
                klasString = [klassenList objectAtIndex:(i - 1)];
            }

            //Check if the string matched or the klas (group of school)
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound ||
                [klasString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound) {
                //Add to results
                [[self searchResults] addObject:currentString];

                //Save the klas (group of school). It has the same index as the result (lastname)
                NSString *strI = [[NSString alloc] initWithFormat:@"%i", i];
                [[self searchResultsLeerlingNaarKlas] addObject:strI];
                [strI release];
            }

            [klasString release];
        }
    }
}

Can someone help me out?

Regards, Dodo


The double free error means you have released an object more than needed. Here the suspicious object is klasString. From your code:

NSString *klasString = [[NSString alloc] init];
...
if(i != -1) {
    klasString = [klassenList objectAtIndex:(i - 1)];
}
...
[klasString release];

The assignment inside the if statement

  1. loses reference to the newly allocated NSString, introducing a memory leak
  2. makes the later release apply to the object from klassenList. When klassenList releases its elements, a double free error will occur.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜