在Swift中,如何从内存中完全删除UIView? [英] In Swift, how to remove a UIView from memory completely?

查看:659
本文介绍了在Swift中,如何从内存中完全删除UIView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class myManager {
    var aView: UIView!

    func createView() {
        aView = UIView()
    }

    func removeView() {
        aView = nil // anything else?
    }
}

如果我这样创建一个UIView,后来又想将其删除,这是正确的方法吗?我应该注意什么?

If I create a UIView like this and later I want to remove it, is this the correct way? Anything I should be aware of?

推荐答案

要取消初始化aView并将其从内存中删除,您需要使任何对此内容有强引用的东西都未引用它.这意味着您的代码的任何部分(UIKit视图堆栈的)都不应引用它.

In order to have aView to be deinitialised and removed from memory you need to make it unreferenced by anything that keeps a strong reference to it. That means it should not be referenced by any part of your code, and by the UIKit view stack.

在您的情况下,它可能看起来像这样:

In your case it might look like this:

aView?.removeFromSuperview() // This will remove the view from view-stack
                             // (and remove a strong reference it keeps)

aView = nil                  // This will remove the reference you keep

另一方面,如果要删除视图,则可能不应该使用var aView: UIView!,而应使用var aView: UIView?.

On a side note, if you are removing the view, then you probably should not use var aView: UIView! but instead var aView: UIView?.

这篇关于在Swift中,如何从内存中完全删除UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆