Resetting a singleton in Objective-C

Resetting singletons can come handy when we want to upd…

Resetting singletons can come handy when we want to update and display same data from different view controllers.

We just write a method inside of the singleton that can reset it for us.
The header would like this


@interface DataController : NSObject
{
NSString  *singletonString;
}

@property (nonatomic, strong) NSString *singletonString;

+(DataController*)sharedInstance;

@end

And we just add the following method into our header

+ (void)resetSharedInstance;

For the implementation we make sure we don’t have a “dispatch_once_t” otherwise once we set the singleton to “nil” we will not be able to reinitialize the singleton and it will remain “nil”.


#import "MySingleton.h"


@implementation DataController
@synthesize singletonString;

static DataController *sharedInstance = nil;
+(DataController*)sharedInstance
    {
 
            {
                if (sharedInstance == nil)
                {
                    sharedInstance = [[DataController alloc]init];
                }
            }
        return sharedInstance;
    }

+ (void)resetSharedInstance {
    sharedInstance = nil;
}
@end

Now we can call the method from any other class after importing the Singleton Class with the following call

[MySingleton resetSharedInstance];

;