子视图控制器中的

子视图控制器中的

本文介绍了子视图控制器中的 UITableView 委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIViewController 调用 Parent,我在 Parent 中有一个 UIView 子视图.我想添加两个不同的可能 UIViewControllers 之一,称为 AB,作为 Parent 的子视图.A 是带有 UITableViewUIViewController.我将AUITableViewdatasourcedelegate设置为A.

I have a UIViewController call Parent, and I have a UIView subview within Parent. I want to add one of two different possible UIViewControllers, called A and B, as subviews of Parent. A is a UIViewController with a UITableView. I set the datasource and delegate of the UITableView in A to A.

然后我可以成功地"将 A 添加到 Parent,如下设置 A 的数据:

I can then "successfully" add A to Parent, setting the data for A as follows:

    AViewController *vc = (AViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"A"];
    NSMutableArray *data = [@[@"foo",@"bar",@"baz"] mutableCopy];
    vc.posts = data;
    [self.container addSubview:vc.view];

通过成功,我的意思是我在单元格中看到了包含正确数据的表格视图.即 foo、bar 和 baz 作为行.

By successful, I mean that I see the tableview with the correct data in the cells. Namely foo, bar, and baz as the rows.

我的问题: 当我尝试滚动 tableview 时,它崩溃了.当我尝试选择一个单元格时,出现以下异常:

My Problem: When I try to scroll the tableview, it crashes. When I try to select a cell, I get the following exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[_UIAppearanceCustomizableClassInfo
tableView:didSelectRowAtIndexPath:]: unrecognized selector sent to instance 0x78c64430'

推荐答案

因为 AViewController 是在上面的代码中本地声明的,所以一旦该代码完成,它就会被释放.因此,当您触摸滚动/选择并调用委托/数据源方法时,delegatedatasource 指向一个完全不同的对象(或根本没有).因此你的崩溃.

Because the AViewController is declared locally in your code above, it is deallocated as soon as that code completes. So when you touch for scrolling/selection and the delegate/datasource methods are called, the delegate and datasource point to a completely different object (or none at all). Hence your crash.

此外,在实现客户容器视图时,您需要实现一些代码,以便父母和孩子都知道.看看 Apple 中的实现自定义容器视图控制器"文档:

Furthermore, when implementing customer container views you need to implement some code so both parent and child know. Take a look at "Implementing a Custom Container View Controller" in the Apple Docs:

    [self addChildViewController:vc];
    [self.container addSubview:vc.view];
    [vc didMoveToParentViewController:self];

我相信 addChildViewController 还将提供从父级到子级 (vc) 的强引用,从而防止它被释放.所以上面的代码应该也解决了释放问题.

I believe the addChildViewController will also provide a strong reference from the parent to the child (vc), thereby preventing it from being deallocated. So the above code should fix the deallocation problem as well.

这篇关于子视图控制器中的 UITableView 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:31