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

前端之家收集整理的这篇文章主要介绍了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

原文链接:https://www.f2er.com/swift/319249.html

猜你在找的Swift相关文章