完全解除分配一个Objective-C单例 [英] Fully deallocating an Objective-C singleton

查看:112
本文介绍了完全解除分配一个Objective-C单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新编写单例,我必须使用一个当前的iOS项目。其中一个要求是它可以被杀死。我知道这违背了单例的设计,但这是应该/可以做的事情。

I'm new to writing singletons and I have to use one for a current iOS project. One of the requirements is that it can be killed. I know this goes against the design of a singleton, but is this something that should/could be done?

推荐答案

可以完成,但如果你正在寻找一个可以创建的对象,然后在不需要的时候释放...这听起来像一个普通的对象。 :)

Of course it could be done, but if you're looking for an object that can be created, and then released when not needed... that sounds like a regular object. :)

通常单例控制自己的生命周期。除非你更多地说两个要求(一个,你使用一个单例,另外两个,它可以随意释放),你会在这里得到一个片面的讨论,以及为什么它们在你的情况下都有意义。

Generally singletons control their own lifecycles. You're going to get one-sided discussion here unless you say more about the two requirements (one, that you use a singleton, and two, that it can be released at will), and why they both make sense in your case.

这可能是因为单例包装了其他固有唯一的资源(如文件资源或网络连接)。如果这是真的,那么通常单例是那个资源的管理者,你通过单例的接口暴露对该资源的控制。

It might be because the singleton wraps some other resource that is inherently unique (like a file resource or network connection). If this is true, then generally the singleton is the "manager" of that resource, and you'd expose control of that resource via the singleton's interface.

因为单例对象持有一吨内存(某种类型的缓冲区),并且你想确保根据需要刷新。如果是这种情况,那么您可以更聪明地了解每个方法根据需要创建和释放内存,或者您可以让单例监听低内存系统通知并正常运行。

Or it might be because the singleton object holds on to a ton of memory (a buffer of some sort), and you want to be sure that's flushed as necessary. If this is the case, then you can be smarter about each of its methods creating and releasing memory as necessary, or you can have the singleton listen for the low memory system notifications and behave appropriately.

本质上,我很难构造一个case,它是真正有意义的单例对象本身被释放。一个单一的基本对象在内存中只占用少量的字节,并且没有人在旁边。

Essentially, I'd be hard pressed to construct a case where it really made sense for the singleton object itself to be released. A single basic object takes only a handful of bytes in memory, and hurts no one by hanging around.

这篇关于完全解除分配一个Objective-C单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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