How to ensure destruction of singleton in IOS 5 with ARC?

无人久伴 提交于 2019-12-01 08:33:18

问题


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.



来源:https://stackoverflow.com/questions/10064238/how-to-ensure-destruction-of-singleton-in-ios-5-with-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!