ios – 可能设置单身回到零吗?

前端之家收集整理的这篇文章主要介绍了ios – 可能设置单身回到零吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经使用常规模式实现了一个单例对象.我的问题是:是否可以将此对象设置为nil,以便稍后调用[MySingleton sharedInstance]对象将被重新初始化?
  1. // Get the shared instance and create it if necessary.
  2. + (MySingleton *)sharedInstance {
  3.  
  4. static dispatch_once_t pred;
  5. static MySingleton *shared = nil;
  6. dispatch_once(&pred,^{
  7. shared = [[MySingleton alloc] init];
  8. });
  9. return shared;
  10. }
  11.  
  12. // We can still have a regular init method,that will get called the first time the Singleton is used.
  13. - (id)init
  14. {
  15. self = [super init];
  16.  
  17. if (self) {
  18. // Work your initialising magic here as you normally would
  19.  
  20. }
  21. return self;
  22. }

我的猜测是这样的

  1. MySingleton *shared = [MySingleton sharedInstance];
  2. shared = nil;

只将本地指针共享为nil.毕竟,共享被声明为静态的.

解决方法

你对本地参考的假设是正确的,它不会影响你的单身人士.

为了能够重新初始化单例,您需要将静态变量从你的方法中移出,所以它可以被整个类访问.

  1. static MySingleton *sharedInstance = nil;
  2. // Get the shared instance and create it if necessary.
  3. + (MySingleton *)sharedInstance {
  4. if (sharedInstance == nil) {
  5. sharedInstance = [[MySingleton alloc] init];
  6. }
  7. return sharedInstance;
  8. }
  9.  
  10. + (void)resetSharedInstance {
  11. sharedInstance = nil;
  12. }

请注意,您不能再使用dispatch_once,因为您的单身明显需要多次创建.如果你只是从你的UI中调用这个单例(因此只从主线程),那么上面的示例是正确的.

如果您需要从多个线程进行访问,则需要对sharedInstance和resetSharedInstance方法进行锁定.

  1. + (id)sharedInstance {
  2. @synchronized(self) {
  3. if (sharedInstance == nil) {
  4. sharedInstance = [[MySingleton alloc] init];
  5. }
  6. return sharedInstance;
  7. }
  8. }
  9.  
  10. + (void)resetSharedInstance {
  11. @synchronized(self) {
  12. sharedInstance = nil;
  13. }
  14. }

这比dispatch_once变体有点慢,但实际上通常并不重要.

猜你在找的iOS相关文章