这与标准singleton pattern稍有不同,因为如果所有对象的外部引用都已释放,那么单例也将被释放。然后,稍后,当请求一个新的对象时,将创建一个新的单例。所以,这样的事情:如何确保Objective-C中任何时候只有一个类的实例?
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下的保留计数。这让我想知道:这甚至有可能吗?
为什么你需要这个? – Abizern 2014-10-31 21:18:05
看起来像通过工厂访问的弱引用会做到这一点。工厂必须像单身工厂一样工作。 – 2014-10-31 21:21:38
因为我不会经常需要这个对象,但是当我这样做时,我会想要一次访问一堆分离的地方中的同一个对象。 – theory 2014-10-31 21:21:52