wagashi
wagashi

Reputation: 894

iOS titleForHeaderInSection crash

The problem is that the two sections are sometimes empty, so I dont know how to prevent crash when they get empty. self.globalSections is a global NSMutableArrays stored by local two NSMutableArrays which are first and second section for my UITableView.

Here is my code:

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

Please point me in the right direction, thanks.

EDIT:

I have modified in this method:

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

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

    //return 1;
}

Is this allright?

Upvotes: 0

Views: 702

Answers (2)

jonkroll
jonkroll

Reputation: 15722

You can avoid repeating code in your titleForHeaderInSection: this way:

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 @"";
    }
}

Upvotes: 2

warrenm
warrenm

Reputation: 31782

Never index into an array whose size you don't know. Always call count or ensure via contract that the array has elements before calling objectAtIndex:. In this case, you need to accurately represent how many non-empty sections you're going to be displaying in your implementation of numberOfSectionsInTableView:.

If you're returning an accurate count of the number of arrays contained in your globalSections array, you'll never run into the situation described above.

Upvotes: 2

Related Questions