Objective-C/iPhone 内存管理静态变量 [英] Objective-C/iPhone Memory Management Static Variables

查看:51
本文介绍了Objective-C/iPhone 内存管理静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态方法,用于创建类的实例并将其放入静态变量中.我想知道在这种情况下内存管理的正确方法是什么.

I have a static method that creates an instance of the class and puts it in the static variable. I am wondering what the proper way of memory management is in this situation.

你不能把它放在 dealloc-method 中,因为虽然它可以访问静态变量,但任何创建的、释放的实例方法也会释放 sharedInstance.

You can't put it in the dealloc-method, because although it can access the static variable any instance method that is created that get's released will also release the sharedInstance.

我想可能有一个选项可以创建一个静态销毁方法,该方法将手动释放内存并可由用户从 appWillTerminate 调用,但这似乎有点奇怪.

I guess there might be an option of creating a static destroy method which will manualy release the memory and can be called by the user from appWillTerminate, but that seems a bit odd.

那么,问题又来了:释放静态变量的正确方法是什么?


// MyClass.m
#import "MyClass.h"

static MyClass *myClass; // How to properly do memory management

@implementation MyClass

+ (MyClass *)sharedMyClass {
    if (myClass == nil) myClass = [[MyClass alloc] init];
    return myClass;
}
@end

推荐答案

你可以不释放它们,这很好,因为应用程序无论如何都会关闭.iPhone 上的 Cocoa 已经这样做了,它不会完全删除所有内容,只会让应用程序被炸毁.

You can either not release them, which is fine since the app is shutting down anyway. Cocoa on the iPhone already does this, it doesn't completely delete everything, it just lets the app get blown away.

或者你可以从 appWillTerminate 或其他一些关闭函数中删除它.

Or you can delete it from appWillTerminate or some other shutdown function.

这篇关于Objective-C/iPhone 内存管理静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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