【发布时间】:2012-01-08 00:18:12
【问题描述】:
我已经阅读了一些关于此问题的 SO 帖子,但似乎遇到了问题(当然包括拉头发)在 UITableView 的顶部添加了一个额外的单元格。这是我的代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// self.StringArray has 5 string objects inside
return ([self.stringArray count] + 1);
}
- (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];
}
// create hardcoded first row in table
if([indexPath row] == 0)
{
cell.textLabel.text = @"Select me";
}
else
{
// decrement the row to get the correct object from the self.stringArray
int arrayIndex = [indexPath row] - 1;
cell.textLabel.text = [self.stringArray objectAtIndex:arrayIndex];
}
return cell;
}
一切看起来都很好(如果我遇到异常错误,显然是有问题),但我似乎无法观察它。
异常:* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]”
【问题讨论】:
-
您是否在 '- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ' 方法的末尾返回单元格?
-
@KrishnaK - 它看起来像一个糟糕的复制/粘贴,所以我将它添加到代码示例中。它存在于我的原始代码中。
-
我在 xcode 中试过了,你的代码执行没有任何异常。据我所知,从这段代码中,stringArray 的内容在上面的两个调用之间被修改了。返回 numberOfRowsInSection 时尝试检查计数值。
-
@KrishnaK - 请参阅下面的答案 =)
标签: objective-c ios ipad uitableview nsarray