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

查看:67
本文介绍了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中,因为尽管它可以访问静态变量,但是任何被get释放的创建的实例方法也将释放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.

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

So, again, the question: What is the proper way of releasing a static variable?


// 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上的可可粉已经做到了这一点,它并没有完全删除所有内容,只是让应用程序被炸掉了.

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天全站免登陆