UITableView和SearchBar问题

时间:2010-05-01 14:22:47

标签: cocoa-touch uitableview iphone-sdk-3.0 uisearchbar uisearchdisplaycontroller

我正在尝试将搜索栏添加到我的UITableView。我遵循了本教程:http://clingingtoideas.blogspot.com/2010/02/uitableview-how-to-part-2-search.html

如果我在搜索框中输入一个字母,我收到此错误:Rooster(10787,0xa05ed4e0) malloc: *** error for object 0x3b5f160: double free *** set a breakpoint in malloc_error_break to debug

此错误发生在此处:

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

    return YES;
}

(在第二行)

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

有人能帮助我吗?

此致 突突

1 个答案:

答案 0 :(得分:2)

双重自由错误意味着您已经释放了一个超过需要的对象。这里的可疑对象是klasString。 从你的代码:

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

if语句中的赋值

  1. 丢失对新分配的NSString的引用,引入内存泄漏
  2. 使后续版本适用于klassenList中的对象。当klassenList释放其元素时,将发生双重自由错误。