How dealloc a Singleton class

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

  1. macrumors newbie

    Joined:
    Jan 17, 2011
    #1
    Hello,

    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. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    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. macrumors 603

    Joined:
    Aug 9, 2009
    #3
    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. macrumors 68040

    Joined:
    Apr 22, 2005
    #4
    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. macrumors newbie

    Joined:
    Jan 18, 2011
    #5
    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. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    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