Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C/iPhone Memory Management Static Variables

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
like image 423
Mark Avatar asked Oct 22 '09 12:10

Mark


1 Answers

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.

like image 88
Roland Rabien Avatar answered Oct 21 '22 12:10

Roland Rabien