How dealloc a Singleton class

Discussion in 'iOS Programming' started by MatteoX, Jan 17, 2011.

  1. MatteoX macrumors newbie

    Jan 17, 2011

    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)

    [[MyClass sharedClass]release];

    the application crash!

    Why? Is there an another way to dealloc a singleton class or a singleton class nevere dealloc?

    Thank you very much!
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  3. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    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.
  4. admanimal macrumors 68040

    Apr 22, 2005
    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.
  5. OpRisk macrumors newbie

    Jan 18, 2011
    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...
  6. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    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.

Share This Page