2012-01-04 96 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