Refactoring and using weak refs to prevent memory leaks.