7

If I declare class variables in Objective-C, when is the memory released?

If my interface is:

@interface TestClass : NSObject
{
}

+ (NSString)instanceCount;

@end

And in the implementation, I declare:

static NSString instanceCount;

How do I release this class level variable? i.e. when is the dealloc called for class variables in Objective-C?

e.James
  • 116,942
  • 41
  • 177
  • 214
user79889
  • 79
  • 1
  • 1
  • 2
  • 3
    Just came across this question while learning Obj-C. Apple seem to suggest that there's no such thing as a "class variable" and what you've defined in the interface is rather a class *method*, that's separate from the static variable and thus needs to be defined in the implementation. The static variable is limited to the scope of the implementation *file*, not the class itself. Maybe this is a minor quibble but it confused me for a sec: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Articles/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-TPXREF118 – James Wheare Oct 11 '09 at 09:31

1 Answers1

10

The short answer to your question is: "when the program exits."

Static variables are allocated at the very beginning of your program, before the main() function begins. Similarly, they will be released at the very end of your program, shortly after main() exits. This memory management is handled by the Objective-C runtime, and it all happens behind the scenes.

If you are trying to monitor this behavior, you probably won't have much luck. For example, if you did the following in a custom class, and then used that class as a static member of another class:

- (void)dealloc
{
    NSLog(@"I am being deallocated");
    [super dealloc];
}

You would never see this message appear in the log. There are a couple of reasons for this. One, the variables that NSLog() requires may already have been deallocated as part of the normal shutdown procedure. And two, because the runtime system may simply release all of the remaining memory in a single shot, without bothering to call the dealloc methods.

This can be problematic if your custom class does something important in its dealloc method. If this is the case, consider writing a custom cleanup method which you call for these objects just before the program exits.

e.James
  • 116,942
  • 41
  • 177
  • 214
  • not to mention the fact that dealloc is an instance method and could get called 0 or 100 times for the class – cobbal Mar 19 '09 at 06:54
  • Hmm, yes, but I was thinking of this method in an object that was used as a static member of another class. I've (hopefully) cleared that up in my answer. Thank you for pointing it out! – e.James Mar 19 '09 at 07:02