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

所以故事就这样:)

我试图阻止枚举NSArray中的对象,并dynamic创build每个UITableViews并将其添加到UIScrollView中。 为了可读性和可重用性,我使用www.objc.io中的Lighter View Controller 。 dataSource被分别为每个UITableView创build。 问题是我一直崩溃

-[NSObject(NSObject) doesNotRecognizeSelector:] 

我从堆栈上的post中发现,块枚举中的对象由于速度问题而保留较弱,并且可以确认dataSource实际上是为每个表取消分配的。

我甚至试图用__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所指出的那样,我将每个数据源都添加到了一个N​​SArray中,这个NSArray已经在块的范围之外初始化了。 这解决了我的问题。 谢谢

正如人们在评论中所说的那样,只要tableviews或者更简单的解决scheme就是使用objc_setAssociatedObject创build强引用,就必须在“活着”的某个地方创builddatasorces

在你的类声明一些static char strongReferenceKey

并在你的块,设置数据源后,做:

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

这种方式将有强大的数据源的参考,这将释放表时被释放。

PS请确保您导入runtime.h:

 #import <objc/runtime.h>