【发布时间】:2012-01-13 21:26:24
【问题描述】:
我正在编写一个应用程序,它从网络上提取一个 .txt 文件,将其解析为一个二维数组(本质上。它实际上是一个 NSMutableArray,每个元素都有一个 NSArray),然后在 UITableView 内显示每个 NSArray(它使用子标签加载每个 NSArray)。
无论如何,一旦我向下滚动到第 17 个单元格(索引为 16),应用就会崩溃...
UITableView 应该有 483 个单元格(用于测试目的),但我似乎无法滚动超过第 16 个单元格而不会崩溃。
编辑以发布代码和错误:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[[tableView layer] setCornerRadius:3.0];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"]autorelease];
}
NSInteger artistIndex = 1;
NSInteger albumIndex = 3;
NSInteger dateIndex = 6;
NSInteger imageIndex = 5;
// ARTIST
CGRect frame = CGRectMake(59, 11, 244, 13);
UILabel *label = [[UILabel alloc]initWithFrame:frame];
label.font = [UIFont boldSystemFontOfSize:13];
label.textColor = [UIColor blackColor];
label.text = [[musicList.list objectAtIndex:indexPath.row] objectAtIndex:artistIndex];
[cell addSubview:label];
// ALBUM (more like description...
frame = CGRectMake(60, 30, 244, 11);
label = [[UILabel alloc]initWithFrame:frame];
label.font = [UIFont boldSystemFontOfSize:11];
label.textColor = [UIColor darkGrayColor];
label.text = [[musicList.list objectAtIndex:indexPath.row] objectAtIndex:albumIndex];
[cell addSubview:label];
// DATE
frame = CGRectMake(59, 49, 244, 10);
label = [[UILabel alloc]initWithFrame:frame];
label.font = [UIFont fontWithName:@"Helvetica" size:10.0];
label.textColor = [UIColor darkGrayColor];
label.textAlignment = UITextAlignmentRight;
label.text = [[musicList.list objectAtIndex:indexPath.row] objectAtIndex:dateIndex];
[cell addSubview:label];
// IMAGE
NSString *urlString = [[musicList.list objectAtIndex:indexPath.row] objectAtIndex:imageIndex];
NSData *urlData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage *myImage = [[UIImage alloc]initWithData:urlData];
UIImageView *myImageView = [[UIImageView alloc] init];
myImageView.image = myImage;
myImageView.frame = CGRectMake(8,9,44,44);
[myImageView.layer setMasksToBounds:YES];
[myImageView.layer setCornerRadius:3.0];
[[cell contentView] addSubview:myImageView];
[urlData release];
[myImage release];
[myImageView release];
[label release];
return cell;
注意:我觉得这段代码很糟糕......如果你们有任何清理它的建议,我很乐意听到。
这是错误消息:
* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[NSMutableArray objectAtIndex:]: index 6 beyond bounds [0 .. 3]”
【问题讨论】:
-
最小的例子有助于理解你遇到的问题。
-
你能把它崩溃时收到的日志声明贴出来吗?
-
看起来与您的数据源方法有关。此方法的哪一行导致崩溃?我感觉您的问题出在其他地方,可能与您如何确定 tableview 上的部分或行数有关。
-
罗格,你是对的。感谢您的建议!
-
这不会回答你的问题,但是在
cellForRowAtIndexPath中创建复杂的单元格对性能没有好处。如果您确实需要这样的单元格,请考虑将UITableViewCell子类化,以便系统可以根据需要将这些单元格出列。只是我的意见。
标签: iphone ios cocoa-touch uitableview uikit