Storyboard segues 导致内存泄漏 [英] Storyboard segues causing memory leaks
问题描述
我有两个 UIViewControllers,它们的按钮可以相互触发 segue(模态).我想知道在来回跳跃时是否会导致任何内存泄漏,我看到了 Living Object &&分配的内存正在增加,最终会导致应用程序崩溃.我没有任何一行代码 - 使用纯 UIViewControllers.
I have two UIViewControllers with buttons triggering segue (modal) to each other. I wanted to discover if that's causing any memory leaks while jumping back and forth and I see that Living Object && allocated memory is going up, what eventually would leave to app crash. I don't have any single line of code - working with pure UIViewControllers.
我可能做错了什么?
我可能在项目设置中设置错误吗?
我是否在阅读分析器的静态学很差?
在使用 segue 时是否需要执行任何特殊的发布命令?
What I might be doing wrong?
Could have I set something wrong in project settings?
Am I reading profiler's statictics badly?
Do I need to make any special release commands while working with segues?
推荐答案
您没有正确使用模态转场.您实现它的方式是,当您转场而不是返回到您来自的实例时,您正在为每个视图控制器创建一个新实例.这就是您的内存使用量不断增加的原因.
You aren't using the modal segues correctly. The way you have implemented it, you are creating a new instance of each view controller when you segue instead of returning to the instance you came from. That is why your memory usage continues to increase.
在 iOS 6 之前,正确的处理方法是:
Before iOS 6, the correct way to handle this was to:
1) 在视图控制器 1
中定义一个方法,例如 viewController2Done
2) 在视图控制器 2 中,创建一个名为 delegate
的属性,其类型为 id
.
3) 在视图控制器 1 的 prepareToSegue
中,将视图控制器 2 中的 delegate
设置为 self
4) 在视图控制器 2 中,当需要返回视图控制器 1 时,调用 [delegate viewController2Done]
5) 在 viewController2Done
调用 [self deniedModalViewControllerAnimated:YES]
1) define a method such as viewController2Done
in view controller 1
2) in view controller 2, create a property called delegate
of type id
.
3) in prepareToSegue
for view controller 1, set delegate
in view controller 2 to self
4) in view controller 2, when it is time to return to view controller 1, call [delegate viewController2Done]
5) in viewController2Done
call [self dismissModalViewControllerAnimated:YES]
此方法在 iOS 6 中仍然有效,但也可以使用新的 unwind segue
代替.要使用它,您需要在视图控制器 1 中定义一个方法,如下所示:
This method still works in iOS 6, but there is also a new unwind segue
that can be used instead. To use it, you would define a method in your view controller 1 like so:
目标 C:
- (IBAction)unwindFromViewController2:(UIStoryboardSegue *)segue
{
NSLog(@"and we are back");
}
斯威夫特:
@IBAction func unwindFromViewController2(_ segue: UIStoryboardSegue) {
print("and we are back")
}
然后,您将控制从视图控制器 2 中的按钮拖动到故事板中视图控制器上方栏中的橙色退出图标.在弹出窗口中,您将选择 unwindFromViewController2
并且瞧,您大功告成了.
Then you'd control drag from the button in view controller 2 to the orange exit icon in the bar above the view controller in the Storyboard. In the pop up, you'd select unwindFromViewController2
and voila, you're done.
这篇关于Storyboard segues 导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!