我有一个包含自定义 UICollectionViewCells 的 UICollectionView(TestReceiptCell 是类名)。
当自定义单元格仅包含 UILabel 时,让 UICollectionView 出现并加载自定义单元格没有任何问题。
然后我通过 IB 将 UITableView 添加到 TestReceiptCell NIB 文件中。我在 TestReceiptCell.h 中为 UITableView 设置了一个引用出口,并在 .m 文件中合成。我将 UITableView 的委托和数据源设置为包含 UICollectionView 的 ViewController。
现在,当运行应用程序时,我在第三行的这个块中得到一个 EXC_BAD_ACCESS 异常:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"TestReceiptCell";
TestReceiptCell *cell = (TestReceiptCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; //exception thrown here
return cell;
}
我运行了 Zombie Instrument 测试,发现释放的内存调用源自这里。这是我第一次使用该仪器,所以我不确定如何从这里进行调查。
作为参考,这里有一些更相关的代码部分:
视图控制器.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.myCollectionView registerNib:[UINib nibWithNibName:@"TestReceiptCell" bundle:nil] forCellWithReuseIdentifier:@"TestReceiptCell"];
// Setup flowlayout
myCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[myCollectionViewFlowLayout setItemSize:CGSizeMake(310, 410)];
[myCollectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.myCollectionView setCollectionViewLayout:myCollectionViewFlowLayout];
self.myCollectionView.pagingEnabled = YES;
}
我也在 ViewController.m 文件中实现 UITableView 数据源和委托方法,但鉴于 EXC_BAD_ACCESS 异常的起源,我不确定问题是否出在此处:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:@"eventCell"];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"eventCell"];
}
return cell;
}
更新:
如果我将 cellForItemAtIndexPath 更改为:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"TestReceiptCell";
//TestReceiptCell *cell = (TestReceiptCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
TestReceiptCell *cell = [NSBundle.mainBundle loadNibNamed:@"TestReceiptCell" owner:self options:nil][0];
return cell;
}
但是,我没有将单元格出列,并且知道这不是正确的方法。在 dequeueReusableCellWithResueIdentifier 创建新单元格时调用的 initWithFrame 方法中似乎存在问题。这是目前的方法:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"TestReceiptCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
编辑:
如果我没有为表格视图选择委托或数据源,则将加载带有表格视图的集合视图。将委托/数据源附加到文件所有者的某些原因导致错误。