You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为ViewController自定义init后self变为nil,messages无法更新如何解决?

问题根因

你在didSelectRowAt方法里创建的ConversationsView实例vc是局部变量,既没有被推入/弹出到视图控制器层级被系统持有,也没有用全局属性保留,方法执行完毕后实例就会被ARC自动释放,等到getAllMessagesForConversation的异步回调执行时,对应的实例已经不存在,weak修饰的self自然就变成nil,导致messages赋值失败。

修复方案

你需要让创建的ConversationsView实例被视图控制器层级持有,避免提前释放,以下是修正后的代码:

class MessagesView: UIViewController {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = conversations[indexPath.row]
        let vc = ConversationsView(with: model.otherUserEmail, convo_id: model.id)
        vc.title = model.name
        let targetUser = connections[indexPath.row]

        // 核心修改:将聊天页推入导航栈,或模态弹出,保证实例被持有
        // 方案1:当前页面在导航栈内时用push逻辑
        self.navigationController?.pushViewController(vc, animated: true)
        // 方案2:需要模态弹出时替换上面代码为下面的逻辑
        // self.present(vc, animated: true)

        dismiss(animated: true, completion: { [weak self] in
            self?.completion?(targetUser)
        })
    }
}

如果你需要先关闭当前MessagesView再打开聊天页,可以把push/present逻辑放到dismiss的回调里,避免视图层级混乱:

dismiss(animated: true, completion: { [weak self] in
    self?.completion?(targetUser)
    self?.navigationController?.pushViewController(vc, animated: true)
})

额外说明

  • 你声明的private var messages = [Message]()初始化逻辑没有问题,不需要修改
  • 回调里的[weak self]写法是正确的,不会产生循环引用,无需调整这部分逻辑

内容的提问来源于stack exchange,提问作者Bina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:24:07