ios - 在 Objective-C 中释放静态资源

标签 ios objective-c macos memory-management singleton

这个问题在这里已经有了答案:





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/

相关文章:

objective-c - 在ios上卸载我的应用程序时如何清理钥匙串(keychain)?

ios - UIView 框架在 UIViewControllerContextTransitioning animateTransition : 中移动时重置

macos - RubyMotion 中的指针与 MacRuby 中的指针

bash - 将输出保存到变量中

ios - UIView 职责(面向对象编程)

ios - 创建 10x10 网格并在控制台中打印它的最佳方法是什么?

c# - GPUImage 和 Monotouch 绑定(bind)或替代方案

ios - 这是什么意思 Apple 实现已被弃用,但仍然可以使用它。不使用它的原因?

objective-c - 可选关系到非可选关系的 CoreData 迁移

macos - 如何在 Mac OSX El Capitan 中安装 gdb(调试器)?