2012-01-04 61 views
0

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

这里是我的代码:

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

这还好吧?

+0

更新与崩溃日志你的问题。 – 0x8badf00d 2012-01-04 20:40:59

回答

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

我试过你的代码,但我仍然得到这样的编译器警告:***终止应用程序,由于未捕获的异常'NSRangeException',原因:'*** - [NSMutableArray objectAtIndex:]:索引0超出空数组的界限' – wagashi 2012-01-05 13:11:39

+0

你能解释一下吗?和:在NSString * matchWord =(sectionCount == 1)中做? @“匹配”:@“匹配”;? – wagashi 2012-01-05 13:12:04

+1

?:是[terniary operator](http://en.wikipedia.org/wiki/%3F :)。当存在if/else条件时,它只是一个更紧凑的方式来为变量赋值。当括号中的条件为真时,表达式将计算为冒号左侧的值,否则计算结果为右侧的值。 – jonkroll 2012-01-05 16:22:02

2

永远不要索引到你不知道的数组中。请致电count或通过合同确认数组中有元素,然后致电objectAtIndex:。在这种情况下,您需要准确地表示您在执行numberOfSectionsInTableView:时要显示多少个非空白部分。

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

+0

所以你说我应该这样写:if([self.globalSections count]> = 2)在我开始在titleForHeaderInSection方法中的这段代码之前? (我不确定count是否为零,如果它包含一个对象,则从1开始) – wagashi 2012-01-04 20:49:22

+1

它是基于零的。是的,你可以做这样的检查,如果不是这样,返回零。 – warrenm 2012-01-04 23:36:29

+0

我也试过这个,但我仍然得到相同的编译器警告。 – wagashi 2012-01-05 13:12:58