objective-c class variables: when is dealloc called?

前端 未结 1 1099
小鲜肉
小鲜肉 2020-12-28 23:39

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

If my interface is:

@interface TestClass : NSObject
{
}

+ (NSString)instan         


        
相关标签:
1条回答
  • 2020-12-29 00:20

    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.

    0 讨论(0)
提交回复
热议问题