问题描述
这与标准单例模式稍有不同,如果释放了对某个对象的所有外部引用,则单身人士也将被释放.然后,稍后,当请求新对象时,将创建一个新的单例.所以,像这样:
This is slightly different from the standard singleton pattern, in that if all external references to an object have released, then the singleton will be released, too. Then, later, when a new object is requested, a new singleton is created. So, something like this:
MyThing *thing1 = [MyThing new];
MyThing *thing2 = [MyThing new];
// thing1 & thing2 are the same object.
thing1 = nil;
thing2 = nil;
thing1 = [MyThing new];
thing2 = [MyThing new];
// thing1 and thing2 are a the same objet, but it's a different object than above.
我试图使用一个弱的静态变量来挂接作用域内的单例,但这没有用,因为我没有办法增加ARC下的保留计数.这让我感到疑惑:这有可能吗?
I tried to use a weak static variable to hang on to my scoped singleton, but that didn't work, since I have no way to increment the retain count under ARC. Which leaves me wondering: is this even possible?
推荐答案
重写allocWithZone:管理单个静态实例.如果为nil,则创建一个新的;如果不是nil,则返回它的保留版本.
override allocWithZone: to manage a single static instance. If nil, makes a new one, if not nil, returns a retained version of it.
实现dealloc,并且在调用nil时是单个静态实例.
implement dealloc and when called nil the single static instance.
我不确定这是否可以在ARC中使用,您可能需要为该文件禁用arc.
I'm not certain if this will work in ARC, you may need to disable arc for that file.
保持物体周围有多贵?遵循标准的单例模式而忘了它无疑省事了.
How expensive is it to keep the object around? It's certainly less hassle to follow a standard singleton pattern and just forget about it.
这篇关于如何确保在Objective-C中任何时候只有一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!