- My question is: is it possible to set this object back to nil, so that on a later called to
[MySingleton sharedInstance]
the object gets re-initialised?
Your assumption about the local reference is correct, it won't affect your singleton.
To be able to reinitialize
the singleton you need to move the static variable out of your method,
so it's accessible by the whole class.
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;
}
Note that you cannot use dispatch_once
anymore, since your singleton needs obviously to be created multiple times.
If you only ever call this singleton from your UI (and therefore only from the main thread),
then the sample above is fine.
If you need access from multiple threads you need to put a lock around the +sharedInstance
and +resetSharedInstance
method, e.g.
+ (id)sharedInstance {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
}
+ (void)resetSharedInstance {
@synchronized(self) {
sharedInstance = nil;
}
}
This is quite a bit slower than the dispatch_once
variant, but in practice it won't matter usually.