how to delete instances after removeFromSuperview?

Hello, what is the proper way to delete completely subviews I added to my superview like this?


for row in (1...cellsPerRow) {    /
            for col in (1...cellsPerCol) {    /
          
                let gameBoardCell = UIView(frame: CGRectMake((cellLength + dividerWidth) * CGFloat(col - 1), (cellLength + dividerWidth) * CGFloat(row - 1), cellLength, cellLength))   
                gameBoard.addSubview(gameBoardCell)
                gameBoardCells.append(gameBoardCell)
     }
}


Later on I'm going to delete these subviews by doing:


for cell in gameBoardCells {
    cell.removeFromSuperview()
    cell = nil
}
gameBoardCells.removeAll()


The "cell = nil" line won't compile because cell was created effectively with a "let". How should I be deleting these subviews completely, ie undo destroy the objects created by UIView(...)? Thanks

Answered by junkpile in 155253022

Just delete that cell = nil line.


In the code you posted, you are only keeping two strong references to each cell. removeFromSuperview() takes care of one, and gameBoardCells.removeAll() takes care of the other. After that no references remain and the object will be deallocated.

Accepted Answer

Just delete that cell = nil line.


In the code you posted, you are only keeping two strong references to each cell. removeFromSuperview() takes care of one, and gameBoardCells.removeAll() takes care of the other. After that no references remain and the object will be deallocated.

Thanks, junkpile. So this is overkill and even though those two code segments will be run many times, I can trust ios will be cleaning it up for me?

Yes I believe the statements on that blog post like "of course, it's still loitering around in memory" are incorrect. An object will only "loiter around in memory" if there is a strong reference to it somewhere. Typically that is the two cases you have: one from the view hierarchy, and one from your code. There may be more if you are doing something fancy but based on the code you posted, that's all there is in your case.


You don't have to trust anything though 🙂 You can test it using the memory leaks tool in Instruments, and/or add a deinit and print some logging there.

Thanks, junkpile!

how to delete instances after removeFromSuperview?
 
 
Q