简体   繁体   English

ios9和ios8中的弱引用

[英]weak reference in ios9 and ios8

[Problem soluted!Just want to know why there is such a difference in ios8 and ios9] I was making a register view controller these days and face with some problem about weak reference. [问题已解决!只想知道ios8和ios9为什么会有这样的区别]我最近正在制作一个寄存器视图控制器,但遇到了一些关于弱引用的问题。

and below is some part of the code(swift) 下面是代码的某些部分(swift)

problem come when I use an iphone6 ios8.1 it crashed. 问题出在我使用iphone6 ios8.1时崩溃了。 And then I noticed that the weak reference is not proper here. 然后我注意到弱引用在这里不合适。 But the code runs well in my ios9 iphone6s. 但是代码在我的ios9 iphone6s中运行良好。 I ran this code on an iphone6 ios8 simulator, app crashed. 我在iphone6 ios8模拟器上运行了此代码,应用崩溃了。 So I think there is some thing different in processing weak reference in ios8 and ios9, But who can explain why..? 因此,我认为在ios8和ios9中处理弱引用有一些不同之处,但是谁能解释原因。

class VC: UIViewController {
    weak var verifyTextField: UITextField?
    override func viewdidload() {
       //....
       verifyTextField = newTextField();
       view.addSubview(verifyTextField!);
    }
    func newTextField() -> UITextField {
        let ntf = UITextField();
        //do some settings to ntf;
        return ntf;
    }
}

You set your new UITextField instance to the weak var verifyTextField but before you add it as a subview (which increments the retain count) it is deallocated (the count is 0 since the var is weak) so verifyTextField! 您将新的UITextField实例设置为weak var verifyTextField实例,但在将其添加为子视图之前(这会增加保留计数),该实例将被释放(由于var弱而计数为0),所以verifyTextField! crashes, the crash you're getting is most likely the famous 崩溃,您遇到的崩溃很可能是著名的

Unexpectedly found nil while unwrapping an Optional 展开Optional时意外发现nil

It's easy to fix it 修复起来很容易

  1. Don't use a weak var 不要使用weak var
  2. Don't force unwrap (use if let instead) 不要强行解包( if let使用if let改用)

The code should be as follows: 代码应如下所示:

class VC: UIViewController {
    var verifyTextField: UITextField? //should not be weak
    override func viewdidload() {
       //....
       verifyTextField = newTextField()
       if let verifyTextField = verifyTextField {
          view.addSubview(verifyTextField!)
       }
    }
    func newTextField() -> UITextField {
        let ntf = UITextField()
        //do some settings to ntf
        return ntf
    }
}

Looks like your object is deallocated instantly after initialization because you don't store any strong reference for it. 看起来您的对象在初始化后立即被释放了,因为您没有为它存储任何强引用。

Try this code: 试试这个代码:

override func viewdidload() {
   //....
   let verifyTextField = newTextField();
   view.addSubview(verifyTextField);
   self.verifyTextField = verifyTextField;
}

Also no need to use weak reference here, because verifyTextField doesn't have reference to your VC, so you won't get a retain cycle. 另外,这里不需要使用weak引用,因为verifyTextField没有对VC的引用,因此您不会获得保留周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM