简体   繁体   English

为什么这是一个保留周期?

[英]Why is this a retain cycle?

I have basic understanding of ARC but in the following example I suddenly get really confused. 我对ARC有基本的了解,但是在以下示例中,我突然感到非常困惑。

FeedViewController has a strong reference of NetworkHelper , then the NetworkHelper has a function which takes a closure and call it later. FeedViewController具有NetworkHelper的强大参考,然后NetworkHelper具有接受闭包并稍后调用的函数。

So here's the confusion: the closure is passed from FeedViewController to NetworkHelper , And this block is not being retained inside NetworkHelper , so why does NetworkHelper has a strong reference of NetworkHelper ? 因此,这里的困惑:封从传递FeedViewControllerNetworkHelper ,而这个块不被保留里面NetworkHelper ,所以为什么NetworkHelper具有很强的参考NetworkHelper this is stated in an article but I just could't figure out why. 这是一篇文章中所述,但我只是头被埋找出原因。 It makes sense to me only if NetworkHelper keep a strong reference to the block. 仅当NetworkHelper对该块保持强烈引用时,这对我才有意义。

class NetworkHelper {
    func getFeed(completion: @escaping ([FeedItem]) -> Void) {
        Alamofire.request(…).responseJSON { (response) in
            if let value = response.result.value {
                if let json = JSON(value)[Constants.items].array {
                    completion(json.flatMap(FeedItem.init))
                }
            }
        }
    }
}

class FeedViewController {
    var tableView: UITableViewController
    var feedItems: [FeedItem]
    var networkHelper: NetworkHelper
    override func viewDidLoad() {
        ...
        networkHelper.getFeed() { items in
            self.feedItems = items
            self.tableView.reloadData()
        }
    }
}

Technically, there is no cycle. 从技术上讲,没有周期。

First of all, NetworkHelper never owns anything, it just passes a closure to Alamofire . 首先, NetworkHelper从不拥有任何东西,它只是将闭包传递给Alamofire

Alamofire holds to that closure, which retains a FeedViewController instance (as self ). Alamofire坚持使用该闭包,该闭包保留了一个FeedViewController实例(作为self )。 However, Alamofire is not owned by FeedViewController , therefore there is no cycle. 但是, Alamofire不属于FeedViewController ,因此没有周期。

It's true that while the request is running, FeedViewController cannot be deallocated because the completion callback prevents that, but that could be an expected behavior and there is definitely no ownership cycle. 的确,当请求运行时,由于完成回调阻止了此操作,因此无法取消分配FeedViewController ,但这可能是预期的行为,并且绝对没有所有权周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM