gpt4 book ai didi

ios - 了解 ViewController dealloc 过程

转载 作者:搜寻专家 更新时间:2023-10-30 20:19:27 24 4
gpt4 key购买 nike

我有一个容器 UIViewController,它在删除其中一个子项时执行以下操作:

- (void)removeChildWithIndex:(NSUInteger)Index {
@autoreleasepool {
ChildViewController *child = [_children objectAtIndex:Index];

//Remove the child from the VC hierarchy
[child willMoveToParentViewController:nil];
[child.view removeFromSuperview];
[child removeFromParentViewController];

//Remove the child from array
[_children removeObjectAtIndex:Index];
}

//Post a notification for anyone who might care
[[NSNotificationCenter defaultCenter] postNotificationName:RemovedChildNotification object:self];
}

我的问题的根源是 child 没有在 @autoreleasepool block 的末尾被 dealloced,而是被释放稍后(在 RunLoop 有机会处理内部未完成事件列表之后的外观):

enter image description here

这通常不会是个问题,但是一个观察在上面函数末尾发送的 NSNotification 的对象依赖于 child dealloc 在它收到通知之前。

任何人都可以解释/将我链接到一些文档以帮助我理解为什么 child 没有立即发布吗?

或者,如果我无法选择何时 childdealloced,有人可以建议一种干净的方法来延迟我的通知,直到 dealloc?我想我可以在 [ChildViewController dealloc] 中调用以通知父级它的消亡并在那时触发通知,但这是一种非常肮脏的方式...

最佳答案

尝试在下一个运行循环迭代中发送通知:

- (void)removeChildWithIndex:(NSUInteger)Index 
{
ChildViewController *child = [_children objectAtIndex:Index];

//Remove the child from the VC hierarchy
[child willMoveToParentViewController:nil];
[child.view removeFromSuperview];
[child removeFromParentViewController];
[child didMoveToParentViewController:nil];

//Remove the child from array
[_children removeObjectAtIndex:Index];

//Post a notification for anyone who might care
[self performSelector:@selector(_postRemoveChildNotification) withObject:nil afterDelay:0.0f];
}

- (void)_postRemoveChildNotification
{
[[NSNotificationCenter defaultCenter] postNotificationName:RemovedChildNotification object:self];
}

关于ios - 了解 ViewController dealloc 过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16647308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com