How to ensure destruction of singleton in IOS 5 wi

2019-02-19 14:09发布

问题:

Say, I want to create a singleton which has some data inside. The data is dynamically allocated only once, as it expected on singleton.

But I would like to now under when and how this data can be is released. Should I establish special method which will destroy the singleton? To be more specific - when the method 'dealloc' for this singleton will be executed? who is responsible for that?

回答1:

You can declare a method/function you call explicitly.

The simplest way is to have a static C++ class hold it, then release it in its destructor. If you have multiple singletons, then this approach does not extend very well because the destruction order is implementation defined.

Another alternative (and better design) would be to avoid the singleton approach, and just use it as a regular instance in another class which lives for the duration of your app (an app delegate is a commonly known example).

As to 'when', it depends on its dependencies and how it's used. It's also good to try to minimize external influence in destruction.



回答2:

In general, a singleton is not different to a normal object. It is freed, if there is no (strong) reference to it anymore. Usually, you control that there is one object only by a static variable. This variable is created at compile time; therefore it can not be freed. But all the 'real' object stuff can.