objective-c类变量:when是什么时候被dealloc调用? [英] objective-c class variables: when is dealloc called?

查看:108
本文介绍了objective-c类变量:when是什么时候被dealloc调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Objective-C中声明类变量,内存何时被释放?

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

如果我的界面是:

@interface TestClass : NSObject
{
}

+ (NSString)instanceCount;

@end

在实现中,我声明:

static NSString instanceCount;

如何释放这个类级别变量?即:当Objective-C中的dealloc调用类变量时?

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

推荐答案

你的问题的简短答案是:程序退出。

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

静态变量在程序的开始处,在 main()函数开始。类似地,在 main()退出后不久,它们将在程序的最后被释放。这个内存管理由Objective-C运行时处理,所有这一切都发生在后台。

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];
}

您永远不会在日志中看到此消息。这有几个原因。一, NSLog()需要的变量可能已经被解除分配作为正常关闭过程的一部分。还有两个,因为运行时系统可以简单地一次释放所有剩余的内存,而无需调用 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.

如果你的自定义类在 dealloc 方法中做一些重要的事情,这可能会有问题。如果是这种情况,请考虑编写一个自定义的清理方法,在程序退出之前调用这些方法。

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.

这篇关于objective-c类变量:when是什么时候被dealloc调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆