does something need to hold a reference to a singleton objective-c object in order to preserve it through the life of an IOS app?

会有一股神秘感。 提交于 2019-12-24 04:05:23

问题


does something need to hold a reference to a singleton objective-c object in order to preserve it through the life of an IOS app?

For example if if AppDelegate you created/instantiated a singleton object but didn't retain it, would this instance (with instance variable data) be available later on in the iPhone app?

In other words to ensure data in the singleton remains intact, in the App Delegate where it was initially created, would the App Delegate need to retain it to one of it's instance variables?


回答1:


No class should need to retain a pointer to a singleton class. Singleton class itself keeps a pointer to its instance. Basically, when the user wants to use a singleton, they will request it through a class method (by convention often starting with shared). This method will check if the singleton has been initialized. If not, it will perform the initialization. If there is already an existing instance in memory, it will just return it. Usually, a singleton object will live in memory for the life of the application.

The point being that, if you set a value for one of the properties, then, yes, it should be accessible in another part of the program. And no, the app delegate does not need to keep a pointer to the singleton.




回答2:


As long as you don't auto release the allocated instance, no.

An explicit allocation needs a release for the object to be freed. So if you just allocate the instance, the object will stay in memory.



来源:https://stackoverflow.com/questions/7815525/does-something-need-to-hold-a-reference-to-a-singleton-objective-c-object-in-ord

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