Question

I have singleton. My singleton has UIViewController property. When I push some view controller I set pushed view controller to the singleton property.

For example I pushed B view controller from A view controller

and inside B view controller initialization code i set the property of singleton:

inside init code:

Singleton *singleton = [Singleton sharedInstance];
singleton.viewController = self;

This code means even when I pop back to previous controller A the instance B never be destroyed as I think and seems I will have memory leak.

So each time when I will push B controller I will increase memory usage.

How can solve it. I have tried use weak instead of strong for singleton property but I am not sure that is the solution.

The expected way for me - something like cascade destroying. But maybe I confused and this code will not cause memory leak. What do you think.

Was it helpful?

Solution

Not really. You aren't leaking the instance because you still have a reference to it. And the memory usage doesn't increase because next time you push B it will set itself to the singleton and replace the previous instance (which will then be deallocated).

Generally, if you do want to store the reference, you should make it 'weak' and / or have the view controller remove itself when it is removed from its parent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top