2012-01-04 6 views
0

問題は、2つのセクションが空の場合があるため、空になるとクラッシュすることを防ぐ方法がわかりません。 self.globalSectionsは、ローカルの2つのNSMutableArraysによって格納されるグローバルなNSMutableArraysで、私のUITableViewの第1および第2のセクションです。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

答えて

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

+0

あなたは何を説明できますか?と:は、NSString * matchWord =(sectionCount == 1)ですか? @ "マッチ":@ "マッチ"; – wagashi

+1

?:は三項演算子です(http://en.wikipedia.org/wiki/%3F :)。これはif/else条件があるときに変数に値を代入するよりコンパクトな方法です。括弧内の条件が真の場合、式はコロンの左側の値に評価され、そうでない場合は右側の値に評価されます。 – jonkroll

2

サイズがわからない配列には絶対にインデックスを付けないでください。 countに電話するか、objectAtIndex:を呼び出す前に配列に要素があることを契約で確認してください。この場合、実装に表示される空でないセクションの数をnumberOfSectionsInTableView:に正確に表現する必要があります。

globalSections配列に含まれる配列の数が正確に返されている場合は、上記の状況に陥ることはありません。

+0

私はtitleForHeaderInSectionメソッドでこのコードを始める前に、if([self.globalSections count]> = 2)のように書くべきだと言っていますか? (私はカウントが0ベースであるかわからない、または1つのオブジェクトが含まれている場合は1で始まる) – wagashi

+1

ゼロベースです。そして、はい、あなたはそのようなチェックをすることができ、それが真でないならnilを返します。 – warrenm

+0

私もこれを試しましたが、私はまだ同じコンパイラ警告を受け取ります。 – wagashi

関連する問題