Aryan C
Aryan C

Reputation: 407

UITableViewCell strong reference cycle, but not being picked up by Leaks in Instruments

I am populating a UITableView with custom UITableViewCells, each having a button in them. To check if a button is pressed, I'm using the delegate protocol pattern. Here is my implementation:

protocol MyTableViewCellDelegate {
    func didPressButtonInTableView(for indexPath: IndexPath)
}

class MyTableViewCell: UITableViewCell {

    lazy var indexPath = (self.superview?.superview as! UITableView).indexPath(for: self)
    var delegate: MyTableViewCellDelegate!

    @IBAction func buttonPressed(_ sender: Any) {
        self.delegate.didPressButtonInTableView(for: self.indexPath!)
    }

}

After reading a bit about memory management, I realized that sometimes, instances of a child class holding references to the parent class do not get deallocated due to a "strong reference cycle", as both the parent class and a child class hold a strong reference to each other. We have to use the weak keyword to define a weak relationship by which, when the parent class is deallocated, the child class will too.

So, I realized that using delegate holds a strong reference to the UITableView (parent class). Running some tests like checking the memory usage in Xcode debugger and using deinit in the child class, I realized that these table view cells were not getting deallocated. Changing the protocol to use AnyObject and then setting the delegate as weak fixed the issue. On running again, memory usage did not keep increasing and deinit was called when I went to a different view.

Running both versions of the code in Leaks in Instruments, there were no memory leaks in the first case, however, there was a very noticeable increase in memory, every time the table view was loaded.

My question is, why is this not marked as a memory leak in Instruments, as the child class is holding a strong reference to parent class using delegate? What is the difference between this and a traditional parent-child string reference that causes leaks caught by Instruments?

Upvotes: 3

Views: 441

Answers (1)

goat_herd
goat_herd

Reputation: 589

That because tableView reuse cell. Since tableview cells are reused, they tend to be only deinited if the tableview itself is deinited. Because even if they are not used right now, the tableview would keep them alive in case they are needed for reuse.

Upvotes: 0

Related Questions