Objective c UITableView上的UISearchBarDelegate和部分问题

Objective c UITableView上的UISearchBarDelegate和部分问题,objective-c,uitableview,uisearchbar,uisearchbardelegate,Objective C,Uitableview,Uisearchbar,Uisearchbardelegate,我在我的UITableView上实现UISearchBarDelegate时遇到了一些问题,其中每当我尝试在UITableView中搜索某些内容时,要么它没有显示所需的结果,要么它会导致应用程序崩溃,并显示一条错误消息: 由于未捕获异常“NSRangeException”而终止应用程序,原因:“***-[\uu NSArrayI objectAtIndex:]:索引1超出边界[0..0]” 下面是我的头文件: #import <UIKit/UIKit.h> @interface V

我在我的UITableView上实现UISearchBarDelegate时遇到了一些问题,其中每当我尝试在UITableView中搜索某些内容时,要么它没有显示所需的结果,要么它会导致应用程序崩溃,并显示一条错误消息:

由于未捕获异常“NSRangeException”而终止应用程序,原因:“***-[\uu NSArrayI objectAtIndex:]:索引1超出边界[0..0]”

下面是我的头文件:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
    UITableView *mainTableView;

    NSMutableArray *contentsList;
    NSMutableArray *searchResults;
    NSString *savedSearchTerm;

    NSMutableArray *ivSectionKeys;
    NSMutableDictionary *ivSectionContents;
}

@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *contentsList;
@property (nonatomic, retain) NSMutableArray *searchResults;
@property (nonatomic, copy) NSString *savedSearchTerm;

@property (nonatomic, retain) NSMutableArray *sectionKeys;
@property (nonatomic, retain) NSMutableDictionary *sectionContents;

- (void)handleSearchForTerm:(NSString *)searchTerm;

@end

我认为我的问题在for循环中,但我不太确定。

您需要更新所有表视图数据源和委托方法来处理这两个表(您只在某些情况下这样做):

应该是:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        NSInteger sections = [self.sectionKeys count];

        return sections;
    } else { // assume it's the search table
        // replace this with the actual result
        return numberOfSectionsForSearchTable;
    }
}

即使过滤了行数组,节号是否正确?sectionKeys/sectionContents也可以访问。是的。我只想搜索sectionContents。我尝试过这样做:if(tableView=[[self-searchDisplayController]searchResultsTableView]){NSInteger sections=[self.sectionContents count];return sections;}否则{NSInteger sections=[self.sectionKeys count];return sections;}但它仍然返回相同的错误。好的,发生了什么?您更新了其余的方法了吗?我只更新了numberOfSectionsInTableView方法。我还需要更新哪些方法?您需要更新所有表视图数据源和委托方法
tableView:numberOfRowsInSection:
tableView:didSelectRowAtIndexPath:
至少(超过您已经完成的操作)。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger sections = [self.sectionKeys count];

    return sections;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        NSInteger sections = [self.sectionKeys count];

        return sections;
    } else { // assume it's the search table
        // replace this with the actual result
        return numberOfSectionsForSearchTable;
    }
}