ios - 在嵌套闭包中声明 weak

标签 ios swift asynchronous

在接下来的 0.5 秒延迟期间,tableViewManager 可能会被释放。我想确保在嵌套闭包内与 textView 交互时 textView 是弱的。我该怎么做?

tableViewManager.textViewDidBeginEditing = { [weak self] textView, indexPath in
    asyncAfter(seconds: 0.5) {
        let value = textView.tag // touched here
        self?.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }
}

编辑:请停止提供有关如何让自己变得虚弱的答案。这个问题不是在问“ self ”。 TextView 。 teeeeexttt viiieeewww。

最佳答案

您可以使用常规语法:

tableViewManager.textViewDidBeginEditing = { [weak self] textView, indexPath in
    // textView is strong here
    asyncAfter(seconds: 0.5) { [weak textView] in
        // textView is weak here
        let value = textView?.tag // touched here
        self?.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }
}

编辑:

尝试使用容器来避免编译器错误:

class WeakLink<T: AnyObject> {
    weak var value: T?

    init(_ value: T) {
        self.value = value
    }
}

tableViewManager.textViewDidBeginEditing = { [weak self] textView, indexPath in
    let weakTextView = WeakLink(textView)
    asyncAfter(seconds: 0.5) {
        // textView is weak here
        let textView = weakTextView.value
        let value = textView?.tag // touched here
        self?.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }
}

关于ios - 在嵌套闭包中声明 weak,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309569/

相关文章:

ios - 安装 SpinWheelControl Cocoapod 出现 "the compiler is unable to type check this expression in time"错误

ios - uicollectionview 重新加载后无法获取单元格

ios - 动画调整全屏 UIView 的大小以在屏幕底部显示另一个 UIView

xcode - 如何在 xcode 中从头开始(Swift 服务器)制作一个新的 Perfect Project?

java - 为什么我的方法不是异步的?

c# - 系统线程任务

ios - View over view 打破层次结构

ios - TableViewCell 中的 Swift 3.0 文本字段未显示

ios - 如何将新的类文件添加到 Xcode 中的组?

node.js - await bcrypt.hash() 与 bcrypt.hashSync() 相同吗?