Short explanation of the issue:
I have a screen in my app which simulates a room with multiple users in it, and the user can click 'next room' and it will push onto the navigation stack another instance of the room view controller. This is a memory usage issue for now, because I simply push another instance onto the stack, which leaves the previous room (which is irrelevant) still allocated in memory as it is still in the navigation stack, and it consumes a lot of memory when there are a lot of chat room instances allocated (for example if a user moves to a lot of different rooms).The navigation stack after a user clicks 'next room':
LoginViewController: 0x142813e00 // [0]
TabBarViewController: 0x140836400 // [1]
LoadingViewController: 0x143813600 // [2]
RoomViewController: 0x13f847400 // [3]
RoomViewController: 0x141824400 // [4]
Index 3 should be deallocated after index 4 has been appended to the stack, I do not need index 3 which is the previous room.
What I've tried:
I've implemented a method to clean up the navigation stack after a new 'RoomViewController' has been appended to the navigation stack.func cleanUpNavigationStack() {
guard let previousRoomVCIndex = self.navigationController?.viewControllers.firstIndex(where:
{ $0 is RoomViewController }) else {return}
self.navigationController?.viewControllers.remove(at: previousRoomVCIndex)
}
I call this method right after pushing the new RoomViewController onto the navigation stack.
So what I've expected to happen is:
1 -> Pushing a new RoomViewController
2 -> Now the navigation stack contains 2 RoomViewControllers, the last one which is the relevant one, and the first one which is the previous irrelevant room.
3 -> I remove the previous irrelevant room from my navigation stack.
4 -> It is being deallocated from memory as well, and if I pop one VC back, it should take me to the LoadingViewController.
But after calling print(navigationController?.viewControllers) when I am done cleaning up the navigation stack, I still see the previous RoomViewController, so the removal didn't work for some reason.
What could be the reason for this? and how should I approach it?
My main goal at the end is to deallocate the current RoomVC when pushing a new RoomVC.