Skip to content

Instantly share code, notes, and snippets.

@arturlector
Last active March 7, 2016 14:31
Show Gist options
  • Save arturlector/8820aa764b0c179eea65 to your computer and use it in GitHub Desktop.
Save arturlector/8820aa764b0c179eea65 to your computer and use it in GitHub Desktop.
Как пересоздать синглтон? Можно ли обнулить объект синглтона?

Как пересоздать синглтон? Можно ли обнулить объект синглтона?

Possible to set singleton back to nil?

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment