菜鸟教程小白 发表于 2022-12-11 18:16:32

ios - 无法形成对类实例的弱引用


                                            <p><p>我收到错误 <code>无法形成对 TestClass 类的实例 (0x15919e00) 的弱引用。可能是这个对象被过度释放,或者正在被释放。</code>下面的代码。</p>

<p>如果我删除 <code>addObserver</code> 和 <code>removeObserver</code> 行,我的代码不会崩溃。我不确定为什么会这样。有没有人有任何想法?提前感谢您的帮助!</p>

<pre><code>class TestClass: NSObject {

   lazy var tableView: UITableView = {

         let tableView = UITableView(frame: .zero, style: .plain)
         tableView.rowHeight = UITableViewAutomaticDimension
         tableView.estimatedRowHeight = 52.0
         tableView.delegate = self
         tableView.dataSource = self

         let nib = UINib(nibName: &#34;CustomCell&#34;, bundle: nil)
         tableView.register(nib, forCellReuseIdentifier: &#34;customCell&#34;)

         tableView.addObserver(self, forKeyPath: &#34;myPath&#34;, options:nil, context: nil)

         return tableView
   }()

   deinit {
         tableView.removeObserver(self, forKeyPath: &#34;myPath&#34;)
   }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>惰性变量和弱引用并没有真正融合在一起。我认为问题在于被声明为惰性变量的 tableView。将其更改为只读变量,您应该没问题... </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 无法形成对类实例的弱引用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45068469/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45068469/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 无法形成对类实例的弱引用