【问题标题】:Why was ViewController instance released when its view still in another view's subview list?为什么 ViewController 实例在它的视图还在另一个视图的子视图列表中时被释放?
【发布时间】:2013-12-15 21:38:15
【问题描述】:

第 1 点。在委托中:

self.friendListVC = [[FriendListVC alloc] init];

第 2 点。 在 FriendCollectionVC.mm 中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    FriendCollectionVC *friendCollectionVC = [[FriendCollectionVC alloc] init];
    [self.view addSubview:friendCollectionVC.view];
}

第 3 点。运行: 使用 lldb:

po [self collectionView].delegate
p [self collectionView]

结果: [没有可用的 Objective-C 描述] (PSTCollectionView *) $6 = 0x212bc400

第 4 点。继续运行。 使用 lldb:

po [self collectionView].delegate
p [self collectionView]

结果:

2013-11-30 00:15:25.637 App[45683:70b] *** -[FriendCollectionVC respondsToSelector:]: message sent to deallocated instance 0x67259eb0
[no Objective-C description available]
(PSTCollectionView *) $6 = 0x6785eca0

同时使用lldb:

po ((MyAppDelegate *)[[UIApplication sharedApplication] delegate]).friendListVC.view
<UIView: 0x6656efa0; frame = (0 0; 945 748); autoresize = W+H; layer = <CALayer: 0x665d0fd0>>

第 5 点。问题: 为什么FriendListVC里面的friendCollectionVC被释放了? AppDelegate 和 AppDelegate.friendListVC 和 AppDelegate.friendListVC.view 都可用。 friendListVC.view 包含子视图friendCollectionVC.view。 - 见代码 2。 该项目正在使用 ARC。

【问题讨论】:

  • 你添加了self.friendListVC = [[FriendListVC alloc] init];到superview?除了 [[alloc]init] 之外,你对它做过什么吗?

标签: ios objective-c uiviewcontroller automatic-ref-counting


【解决方案1】:

您没有保留任何指向friendCollectionVC 的强指针,因为您将其创建为局部变量。将其视图添加为子视图不会改变这一事实。无论如何,将一个控制器的视图添加为另一个控制器视图的子视图并不是一个好主意。当您将friendCollectionVC 的视图添加为FriendListVC 的视图的子视图时,您应该使用自定义容器控制器api 使friendCollectionVC 成为FriendListVC 的子视图控制器。如果这样做,FriendListVC 将有一个指向friendCollectionVC 的强指针(在其childViewControllers 数组中)。

- (void)viewDidLoad {
    [super viewDidLoad];
    FriendCollectionVC *friendCollectionVC = [[FriendCollectionVC alloc] init];
    [self addChildViewController:friendCollectionVC];
    [friendCollectionVC didMoveToParentViewController:self];
    [self.view addSubview:friendCollectionVC.view];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多