When i was going through Singleton design pattern in Objective C, I found lot of people using the below code to create it.
@interface Base : NSObject {}
+(id)instance;
@end
@implementation Base
+(id) instance
{
static id theInstance = nil;
if (theInstance == nil)
{
theInstance = [[self alloc] init];
}
return theInstance;
}
@end
Here i did not get the why do we have to assign the static variable to nil in a method instead it can be declared outside the method and assigned to nil. Because everytime this +instance() method is called, theInstance variable will be assigned to nil. Will it not lose its previous object to which it was pointing to?
I have tried debugging it, surprisingly , it will not point to nil when +instance() method is called. Can anyone explain me whats happening here?