Swift:弱引用存储和嵌套块/闭包

Swift: Weak referenced stored & nested blocks / closures

我正在寻找嵌套块/闭包,而另一个进程像这样从主线程完成

typealias FirstBlock = (jsonDictionary:NSDictionary?,errorCode:NSString?) -> Void

typealias SecondBlock = (complete:Bool?,errorCode:NSString?,dictionary:NSDictionary?) -> Void

我遗漏了一些关于 ARC 保留周期的基本知识,因为每次调用其中一个时我都会发生内存泄漏..我已经看过了 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html 没有喜悦..我认为 Defining a Capture List 是正确的区域,但是至于存储块以及如何定义它我不知道我做错了什么。

很可能,您获得了保留周期,因为完成块引用了 HttpRequest(可能通过调用对象),引用了完成块,例如:

class HttpReference {
    let completion : ()->()

    init(completion:()->()) {
        self.completion = completion
    }
}

class Owner {
    var httpReference : HttpReference?

    func someFunction() {
        httpReference = HttpReference() {
            print(self.httpReference)
        }
    }
}

有两种方法可以打破循环,使用 unowned 引用或使用 weak 引用,两者非常相似,在这种情况下,规范是通过更改使用对自身的无主引用:

func someFunction() {
    httpReference = HttpReference() { [unowned self] in
        print(self.httpReference)
    }
}

现在,self 未保留,因此打破了保留循环。