Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c class variables: when is dealloc called?

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?

like image 403
user79889 Avatar asked Mar 19 '09 06:03

user79889


People also ask

How do I use Dealloc in Objective-C?

When you have 3 instances of the object in your code, and you do an [object1 release] on (let's say) the first object, you still have 2 instances left elsewhere, so it isn't called yet. You'll need to release all instances of the object in order for dealloc to be called.

What is Dealloc in C?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.

What is a static variable in Objective-C?

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.


1 Answers

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.

like image 107
e.James Avatar answered Nov 03 '22 00:11

e.James