在数组块枚举中创建 UITableViews 会导致崩溃

creating UITableViews in array block enumeration causes crash

所以故事是这样的:)

我正在尝试阻止 NSArray 中的枚举对象,并为每个对象动态创建 UITableView,并将它们添加到 UIScrollView 中。为了可读性和可重用性,我使用 Lighter View Controllers from www.objc.io。分别为每个 UITableView 创建数据源。问题是我一直崩溃

-[NSObject(NSObject) doesNotRecognizeSelector:]

我从堆栈上的帖子中发现,出于速度考虑,块枚举中的对象保留较弱,并且可以确认每个 table.

的数据源实际上已被释放

我什至尝试用 __strong 初始化 ArrayDataSource 但没有效果。

__strong ArrayDataSource *customdayTableDataSource = [[ArrayDataSource alloc] initWithConfigureCellBlock:configureCell cellIdentifier:DayTableCellIdentifier];

我在街区做错了什么?你能给我指出正确的方向吗?

TableViewCellConfigureBlock configureCell = ^(id cell, id object) {
    [cell configureForObject:object];
};

[NSArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    int tableHorizontalPosition = [[UIScreen mainScreen] bounds].size.width * idx;               
    int tableHeight = [[UIScreen mainScreen] bounds].size.height; 

    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(tableHorizontalPosition, 0, [[UIScreen mainScreen] bounds].size.width, tableHeight) style:UITableViewStylePlain];

    [table setDelegate:self];

    ArrayDataSource *customDataSource = [[ArrayDataSource alloc] initWithConfigureCellBlock:configureCell cellIdentifier:MyCellIdentifier];

    [customTableDataSource setOriginalData:[NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil]];

    [table setDataSource:customTableDataSource];

    [[self myUIScrollView] addSubview:table];

}];

正如 rmaddy 所指出的,我将每个数据源添加到一个在块范围之外初始化的 NSArray。这解决了我的问题。谢谢

正如人们在评论中所说的那样,您必须在 "alive" 与 table 视图一样长的地方创建数据源,或者更简单的解决方案是使用 [= 创建强引用26=]

在你的 class 中声明一些 static char strongReferenceKey

在您的块中,设置数据源后,执行:

objc_setAssociatedObject(table, &strongReferenceKey, customDataSource, OBJC_ASSOCIATION_RETAIN);

这样 table 将对数据源有很强的引用,当 table 被释放时将被释放。

P.S。确保导入 runtime.h:

#import <objc/runtime.h>