UITableView数据源方法的奇怪行为

时间:2013-12-06 18:12:22

标签: ios objective-c cocoa-touch uitableview ios7

我想创建一个UIViewController类,其中包含标准tableview数据源方法(-cellForRowAtIndexPath:-numberOfRows等)的默认实现。

我想创建一个自定义下拉列表。

以下是我的问题的详细解释:
我定义了MyDropDownListController类,它使用名为UITableViewDelegate的{​​{1}} ivar来实现UITableViewDataSourceUITableView协议。

然后,我定义了一个自定义配置方法:

table

然后我定义-(void)initDropDownListWithItems:(NSArray*)items andAddToView:(UIView*)view { dropDownItems = items; //data source array of items to display in list table = [[UITableView alloc] initWithFrame: CGRectMake(view.frame.origin.x, view.frame.origin.y + view.frame.size.height + 1, view.frame.size.width, 140)]; [view addSubview:table]; //add my table to view [table setDataSource:self]; [table setDelegate:self]; [table reloadData]; } -numberOfRowsInSection:等 在此之后,在其他一些cellForRowAtIndexPath类(,我想要我的下拉列表)中,我有这个:

UIViewController

启动应用程序后,当显示此列表时,我会遇到奇怪的例外情况:

  

- [_ UIParallaxDimmingView tableView:numberOfRowsInSection:]:无法识别的选择器发送到实例0x16500c70

正如您所看到的,dataSource = @[@"first", @"second", @"third"]; MyDropDownListController * list= [[MyDropDownListController alloc] init]; [list initDropDownListWithItems:dataSource andAddToView:someViewInThisController]; 没有调用数据源方法,而是针对其他一些奇怪的事情。

这些消息可能略有不同:

  

[UIBarButtonItem tableView:numberOfRowsInSection:]:无法识别   选择器已发送

等等。

我希望你能看到问题 似乎我没有像{I} MyDropDownListController那样调用数据源方法:

MyDropDownListController

但是对于其他一些东西。

1 个答案:

答案 0 :(得分:4)

我的猜测是,将表作为类变量的视图控制器正在被释放,因为它在函数末尾的引用计数为0。当你做类似的事情时:

{
dataSource = @[@"first", @"second", @"third"];
MyDropDownListController * list= [[MyDropDownListController alloc] init];
[list initDropDownListWithItems:dataSource andAddToView:someViewInThisController];
}

在函数结束时,ARC会通过并将内存标记为可重用,如果它不再被任何内容引用。您正在引用控制器作为tableview的委托,但委托是弱引用,不计入ARC。因此,您获得无法识别的选择器的原因是因为ARC标记了重用的内存位置,然后操作系统通过在其中放置新对象来重新使用它。然后你的表调用它的委托(由于操作系统重新填充内存,它仍然是一个有效的对象),你得到一个无法识别的选择器错误。如果您没有在发生这种情况时创建对象,那么您将收到一个可以通过NSZombies追踪的bad access错误。