Swift 中的块引用

block reference in Swift

我有一个 swift NSURLConnection 块。

NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var err: NSError
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    self.updateDataToPlace(jsonResult)                  
})

Question: 像上面那样使用self.updateDataToPlace(jsonResult)安全吗?

在objective-C中,我通常会为这样的事情做一个弱引用。

__weak typeof(self) weakSelf = self;

在(响应:但在 { 您需要捕获列表之后。

对于您在 ObjC 中的使用

[weak self]

请注意,如果您将变量设置为 weak,则释放速度会变慢(加上所有更常见的陷阱)。

你也可以试试

[unowned self]

这可能会更快,但只有在您知道该块的寿命不能超过该对象时才使用它,否则调试起来会一团糟。

有关详细信息,请查找 capture list on Apple's documentation

在这种情况下,self 没有对该块的引用,因此您不需要使 self 变弱。但是如果你这样做了,你会像@Stripes 提到的那样使用捕获列表。在这种情况下,self 也将成为可选项。

所以像这样:

NSURLConnection.sendAsynchronousRequest(request1, queue: nil) { [weak self] response, data, error in
    var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
    self?.updateDataToPlace(jsonResult)
}

(我稍微更新了您的代码以使其更简洁并使用尾随闭包语法)