View Full Version : How dealloc a Singleton class
Jan 17, 2011, 11:28 AM
In my project I need a Singleton class for shared data. When I change scene i would like to dealloc this Singleton class because I don't need it again. The retain count of this class is 1 and when i try to execute code (when i change view)
the application crash!
Why? Is there an another way to dealloc a singleton class or a singleton class nevere dealloc?
Thank you very much!
Jan 17, 2011, 12:22 PM
The answer depends on how you've implemented your singleton. Maybe you really don't want a singleton. Anyhow, think about adding a method to the singleton class (finished or something like that), which releases the object and sets it to nil and does any required cleanup.
Jan 17, 2011, 12:53 PM
1. Post the code for MyClass.
2. Run your program under Instruments, with Zombies enabled. I would bet that somewhere your code is actually still using the singleton. I would also bet you didn't set the singleton variable itself to nil, so it's returning the dealloc'ed instance.
Jan 17, 2011, 03:42 PM
The fact that you're inclined to deallocate your singleton while the app is still running makes me wonder if it should be a singleton.
Jan 18, 2011, 10:30 PM
Wirelessly posted (Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5)
Try using autorelease on your singleton object. If you send a specific release message will lose the pointer to the object before another object can access it thus causing it to crash.
Using autorelease will put the object in the general release pool to get deallocated at some point.
At least it is how I understand it...
Jan 19, 2011, 10:45 AM
I don't think autorelease is the solution for a singleton either. You need to think about the purpose of this object and whether a singleton for it is really the right answer. Perhaps you can elaborate more on what it's for, how many other objects are sharing its data, and why you need to get rid of it when there's a new scene.