swift – 关闭时对属性的引用需要明确的“自我”.使捕获语义显式化

尝试将 HTML从Web服务加载到webview中,我收到此错误

Reference to property ‘webviewHTML’ in closure requires explicit ‘self.’ to make capture semantics explicit

它是什么意思,我如何将HTML字符串加载到我的Web视图中?

func post(url: String,params: String) {

    let url = NSURL(string: url)
    let params = String(params);
    let request = NSMutableuRLRequest(URL: url!);
    request.HTTPMethod = "POST"
    request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data,response,error in

        if error != nil {
            print("error=\(error)")
            return
        }

        var responseString : Nsstring!;
        responseString = Nsstring(data: data!,encoding: NSUTF8StringEncoding)
        webviewHTML.loadHTMLString(String(responseString),baseURL: nil)
    }
    task.resume();
}
在回答这个问题之前,你必须知道记忆周期是什么.见 Resolving Strong Reference Cycles Between Class Instances From Apple’s documenation

现在你知道什么是内存周期了:

那个错误是Swift编译器告诉你的

hey the NSURLSession closure is trying to keep webviewHTML in
the heap and therefor self ==> creating a memory cycle and I don’t
think Mr.Clark wants that here. Imagine if we make a request which takes
forever and then the user navigates away from this page. It won’t
leave the heap.I’m only telling you this,yet you Mr.Clark must create a weak reference to the self and use that in the closure.”

我们使用[弱自我]创建(即capture)弱引用.我强烈建议您查看附加链接的捕获方式.

欲了解更多信息,请参阅斯坦福大学课程this moment.

正确的代码

func post(url: String,params: String) {

    let url = NSURL(string: url)
    let params = String(params);
    let request = NSMutableuRLRequest(URL: url!);
    request.HTTPMethod = "POST"
    request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        [weak weakSelf self] data,encoding: NSUTF8StringEncoding) 

        weakSelf?.webviewHTML.loadHTMLString(String(responseString),baseURL: nil)
        // USED `weakSelf?` INSTEAD OF `self` 
    }
    task.resume();
}

有关详细信息,请参阅此Shall we always use [unowned self] inside closure in Swift

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...