I have a static method that creates an instance of the class and puts it in the static variable. I am wondering what the proper way of memory management is in this situation.
You can't put it in the dealloc-method, because although it can access the static variable any instance method that is created that get's released will also release the sharedInstance.
I guess there might be an option of creating a static destroy method which will manualy release the memory and can be called by the user from appWillTerminate, but that seems a bit odd.
So, again, the question: What is the proper way of releasing a static variable?
// MyClass.m
#import "MyClass.h"
static MyClass *myClass; // How to properly do memory management
@implementation MyClass
+ (MyClass *)sharedMyClass {
if (myClass == nil) myClass = [[MyClass alloc] init];
return myClass;
}
@end
You can either not release them, which is fine since the app is shutting down anyway. Cocoa on the iPhone already does this, it doesn't completely delete everything, it just lets the app get blown away.
Or you can delete it from appWillTerminate or some other shutdown function.
static variable or class remains in memory Untill lifetime of your application
So if it is UnUsed then make
while declaring use static _datatype variable = nil; which help while initializing .. and memory management
You'll want to have a look at "Creating a Singleton" on the iPhone dev center to see how to properly implement that pattern. You won't be releasing your singleton, just letting it die when the application exits.
Also, if you're multithreaded you'll probably want to wrap that alloc in a @synchronize( self ) {}
Here is the full text:
UPDATE: There is now a much easier way to create a singleton
Using this new style you don't need to worry about the
@syncronize
or overriding the memory management methods.