0

如果我只加载一个表格视图,我的视图中必须有两个表格视图,它工作正常。但是,当我尝试使用以下方法加载两个表格视图时,它给出了以下异常。

未捕获的异常 'NSRangeException',原因:' * -[NSArray objectAtIndex:]: index 2 beyond bounds [0 .. 1]'

- (void)viewDidLoad {
[super viewDidLoad];

array1 = [[NSArray alloc]initWithObjects:@"Start",@"End",@"Frequency",@"Time of Day",nil];
array2 =[[NSArray alloc]initWithObjects:@"Alarm",@"Tone",nil];

table1.scrollEnabled =NO;
table2.scrollEnabled =NO;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == table1) ;
   return 1;

if (tableView == table2); 
    return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.table1) ;
    return [array1 count];
if (tableView == self.table2) ;
    return [array2 count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...


if (tableView == self.table1){
    cell.textLabel.text = [array1 objectAtIndex:indexPath.row];     

}
if (tableView == self.table2){
    cell.textLabel.text = [array2 objectAtIndex:indexPath.row];     

}
return cell;}
4

1 回答 1

1

您可能在索引处请求一个大于您的数组之一的对象。您是否正确实施– numberOfSectionsInTableView:– tableView:numberOfRowsInSection:检查它们调用哪个表并根据您的数据数组返回适当的值?
更新
以这种方式编辑方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    if (tableView == self.table1)
       return 1;

    if (tableView == self.table2)
       return 1;

    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.table1)
        return [array1 count];
    if (tableView == self.table2)
        return [array2 count];

    return 0;
}
于 2012-04-20T09:32:20.677 回答