加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:27:28 所属栏目:百科 来源:网络整理
导读:尝试将 HTML从Web服务加载到webview中,我收到此错误: Reference to property ‘webviewHTML’ in closure requires explicit ‘self.’ to make capture semantics explicit 它是什么意思,我如何将HTML字符串加载到我的Web视图中? func post(url: String,p
尝试将 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读