简体   繁体   中英

Why is this a retain cycle?

I have basic understanding of ARC but in the following example I suddenly get really confused.

FeedViewController has a strong reference of NetworkHelper , then the NetworkHelper has a function which takes a closure and call it later.

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 ? 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.

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 .

Alamofire holds to that closure, which retains a FeedViewController instance (as self ). However, Alamofire is not owned by FeedViewController , therefore there is no cycle.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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