// Get the shared instance and create it if necessary.+ (MySingleton *)sharedInstance { static dispatch_once_t pred; static MySingleton *shared = nil; dispatch_once(&pred,^{ shared = [[MySingleton alloc] init]; }); return shared;}// We can still have a regular init method,that will get called the first time the Singleton is used.- (ID)init { self = [super init]; if (self) { // Work your initialising magic here as you normally would } return self;}
我的猜测是这样的
MySingleton *shared = [MySingleton sharedInstance];shared = nil;
只将本地指针共享为nil.毕竟,共享被声明为静态的.
解决方法 你对本地参考的假设是正确的,它不会影响你的单身人士.为了能够重新初始化单例,您需要将静态变量从你的方法中移出,所以它可以被整个类访问.
static MySingleton *sharedInstance = nil;// Get the shared instance and create it if necessary.+ (MySingleton *)sharedInstance { if (sharedInstance == nil) { sharedInstance = [[MySingleton alloc] init]; } return sharedInstance;}+ (voID)resetSharedInstance { sharedInstance = nil;}
请注意,您不能再使用dispatch_once,因为您的单身明显需要多次创建.如果你只是从你的UI中调用这个单例(因此只从主线程),那么上面的示例是正确的.
如果您需要从多个线程进行访问,则需要对sharedInstance和resetSharedInstance方法进行锁定.
+ (ID)sharedInstance { @synchronized(self) { if (sharedInstance == nil) { sharedInstance = [[MySingleton alloc] init]; } return sharedInstance; }}+ (voID)resetSharedInstance { @synchronized(self) { sharedInstance = nil; }}
这比dispatch_once变体有点慢,但实际上通常并不重要.
总结以上是内存溢出为你收集整理的ios – 可能设置单身回到零吗?全部内容,希望文章能够帮你解决ios – 可能设置单身回到零吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)