我已经使用常规模式实现了一个单例对象.我的问题是:是否可以将此对象设置为nil,以便稍后调用[MySingleton sharedInstance]对象将被重新初始化?
- // 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变体有点慢,但实际上通常并不重要.