iOS titleForHeaderInSection崩溃

时间:2012-01-04 20:26:56

标签: ios uitableview title

问题是这两个部分有时是空的,所以我不知道如何在它们变空时防止崩溃。 self.globalSections是由本地两个NSMutableArrays存储的全局NSMutableArrays,它们是我的UITableView的第一和第二部分。

这是我的代码:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{

    if (mySearchBar.text.length > 0)
    {
        if(section == 0)
        {
            //below are if statements I have tried, but not working...
            //NSUInteger globalSectionsOne = [self.globalSections indexOfObject:[self.globalSections objectAtIndex:0]];
            //if ([[self.globalSections objectAtIndex:0]count] >=1)
            //  if (globalSectionsOne!=NSNotFound)
            //if (globalSectionsOne >= 1)

            //{
                NSLog(@"sections counts");
                NSUInteger firstSectionCount = [[self.globalSections objectAtIndex:0]count];

                NSString *firstSectionString = [NSString stringWithFormat:@"%i Exact match(es)", firstSectionCount];

                return firstSectionString;
            //}
            //else {return @"";}

        }
        else if (section == 1)
        {
 //another same code, except the objectAtIndex is at 1 instead of 0.

请指出正确的方向,谢谢。

编辑:

我已修改过这种方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if (mySearchBar.text.length > 0 && [self.globalSections count] == 2)
    {
        return 2;
    }
    else 
    {
        return 1;
    }

    //return 1;
}

这样好吗?

2 个答案:

答案 0 :(得分:2)

永远不要索引到您不知道其大小的数组。在调用count之前,始终调用objectAtIndex:或通过合同确保数组具有元素。在这种情况下,您需要准确地表示您将在numberOfSectionsInTableView:的实施中显示的非空部分的数量。

如果您返回globalSections数组中包含的数组数的准确计数,您将永远不会遇到上述情况。

答案 1 :(得分:2)

您可以避免以titleForHeaderInSection:方式重复代码:

if (mySearchBar.text.length > 0)
{
    if ([self.globalSections count] > section)
    {
        int sectionCount = [[self.globalSections objectAtIndex:section] count];
        NSString *matchWord = (sectionCount == 1) ? @"match" : @"matches";
        return [NSString stringWithFormat:@"%i Exact %@", sectionCount, matchWord];
    }
    else
    {
        return @"";
    }
}
相关问题