ios:为什么它会马上叫deinit [英] ios: why it call deinit immediately

查看:135
本文介绍了ios:为什么它会马上叫deinit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我遇到了一个问题,vc从不打电话给deinit,所以我加了一个弱的

today I faced a problem , the vc never call deinit, so I added a weak

func showAddCityViewController() {
        weak var vc:SWAddCityViewController!
        vc =  SWAddCityViewController()
        vc.delegate = self
        let nav = UINavigationController(rootViewController: vc)
        dispatch_async(dispatch_get_main_queue(), {
            self.presentVC(nav)
        })
    }

我运行此函数然后得到一个

I run this function and then get a


致命错误:在解包可选值时意外发现nil

fatal error: unexpectedly found nil while unwrapping an Optional value

vc只是为了nil,但我不知道为什么,我该怎么办才能使这段代码感到满意?

the vc just go to nil ,but I don't know why , what should I do to make this code happy?

推荐答案

你写了这个:

    weak var vc:SWAddCityViewController!
    vc =  SWAddCityViewController()

vc 变量是隐式解包的可选,这意味着它可以指向现有的(未解除分配的)对象,也可以为零。

The vc variable is an "implicitly unwrapped Optional", which means it can either point to an existing (not-deallocated) object, or it can be nil.

你创建一个新的 SWAddCityViewController 对象并将其分配给 vc 。赋值语句完成后,只有一个对新对象的弱引用(在 vc 中),并且没有强引用。一旦对象没有强引用就会被释放,因此一旦赋值语句完成就会释放它。

You create a new SWAddCityViewController object and assign it to vc. After the assignment statement completes, there is exactly one weak reference to the new object (in vc) and there are no strong references to it. An object is deallocated as soon as it has no strong references, so it is deallocated as soon as the assignment statement completes.

因为 vc 是对象的弱引用,部分是将对象集 vc 解除分配为nil。当您尝试在下一行设置 vc.delegate 时,Swift会生成代码以自动解包 vc (因为您声明了它与)。由于 vc 为零,因此会出现致命错误。你不能打开一个设置为nil的可选项,因为它没有包装任何内容。

Since vc was a weak reference to the object, part of deallocating the object sets vc to nil. When you try to set vc.delegate on the next line, Swift generates code to unwrap vc automatically (since you declared it with !). Since vc is nil, you get a fatal error. You cannot unwrap an optional that's set to nil because it's not wrapping anything.

我认为没有理由声明 vc 该功能很弱。只需摆脱属性。

I don't see any reason to declare vc weak in that function. Just get rid of the weak attribute.

您的其他投诉是()该对象稍后不会被释放。你有一个保留周期。您是否使用声明 SWAddCityViewController 委托属性?您通常要声明委托属性

Your other complaint is that (with weak) the object doesn't get deallocated later. You have a "retain cycle". Did you declare the delegate property of SWAddCityViewController using weak? You usually want to declare delegate properties weak.

如果这不能解决问题,您需要寻找其他涉及对象的保留周期的地方。

If that doesn't fix the problem, you need to look for other places where you have a retain cycle involving the object.

这篇关于ios:为什么它会马上叫deinit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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