这个问题在这里已经有了答案:
Objective-C/iPhone Memory Management Static Variables
(3 个回答)
9年前关闭。
如果我在 Objective-C 类中使用静态资源,我会不会因为不释放它而造成内存泄漏?类似于以下内容:
@interface MyClass : NSObject
+ (MyClass *)sharedInstance;
@end
@implementation MyClass
+ (MyClass *)sharedInstance
{
static MyClass * inst;
if (!inst)
inst = [MyClass new];
return inst;
}
@end
A) 是否存在使用此类的应用程序关闭并且此静态声明会造成内存泄漏的情况?
B) 有没有类方法,如
+ (void)unloadClassDefinition
,当从内存中清除类定义时调用? (这甚至会发生吗?)
最佳答案
泄漏是您丢失了所有指针的一 block 内存。你总是有一个指向这个对象的指针,因为这个变量在你的过程中存在。只要在不破坏旧对象的情况下不将新对象重新分配给该指针,就永远不会发生泄漏。
A)当它终止时,你的所有进程的内存都会被回收。没有泄漏这样的事情可以持续到您的应用程序结束之后。
B) 一旦在 Apple 的 ObjC 运行时加载,类就永远不会被卸载。
如果您希望能够销毁此对象,则必须将变量移出该方法,以便您可以从另一个方法访问它,并按照以下方式执行操作:
static MyClass * inst;
+ (MyClass *)sharedInstance
{
if (!inst)
inst = [MyClass new];
return inst;
}
// Under ARC; under MRR you might monkey around with retain and release
// This won't actually immediately destroy the instance if there are other
// strong references to it.
+ (void)destroySharedInstance
{
inst = nil;
}
但一般来说,如果您使用的是单例,您可能希望在应用程序的整个生命周期中都使用它。
关于ios - 在 Objective-C 中释放静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805175/