简体   繁体   English

为ui元素分配弱引用时,为什么我的应用程序崩溃?

[英]Why my app crashes, when assigning a weak reference to ui elements?

My app crashes when assigning ui elements weak reference in code, though by default when using storyboards ui elements are forced to be assigned weak reference. 在代码中分配ui元素弱引用时,我的应用程序崩溃了,尽管默认情况下,使用情节提要时,ui元素被强制分配了弱引用。

class UploadContactShowViewController: BasePage,UITableViewDelegate,UITableViewDataSource, DARChatPhoneShowCellDelegate {

    var counter = 0

    var delegate: UploadContactShowViewControllerDelegate?
    var contact: APContact?

    var contactSelected: APContact?
    var contacts: [DARContact] = []
    var selectedContacts: [DARContact]!
    var checkBoxs: [BEMCheckBox]!

    var avatarImageView: UIImageView!
    var fullNameLabel: UILabel!
    var tableView: UITableView!
}

When a Storyboard (or a xib) unarchives the UI elements it adds them as subviews to the existing view. 情节提要(或xib)取消存档UI元素时,会将其作为子视图添加到现有视图中。 Because of this there is a strong reference (subviews are strongly referenced) and although IBOutlets are weak, there is a strong reference to prevent them from being deallocated. 因此,有一个很强的参考(强烈引用了子视图),尽管IBOutlets很弱,但是有一个强大的参考可以防止它们被释放。

If you are creating views in code and adding them to weak references, unless you have already added them as a subview, there is no reference so nothing is holding onto these UI Items, so they are deallocated. 如果要在代码中创建视图并将它们添加到weak引用中,除非您已经将它们添加为子视图,否则就没有引用,因此这些UI项没有任何保留,因此将它们释放。

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

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