0

I followed a tutorial to implement Singleton and its working fine .Below is the code:

@implementation DKSingle

static DKSingle *dKSingle = nil;

+(id)dKSingleInstance{

    if (!dKSingle) {
        dKSingle = [[DKSingle alloc]init];
    }
    return dKSingle;
}


-(id)init{

    if (!dKSingle) {
        dKSingle = [super init];
    }
    return dKSingle;
}

@end

My question is dKSingle is a static variable, then how come it works inside the instant method init . Please help me to understand.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
dinesh
  • 72
  • 1
  • 7
  • You can use static variables in instance methods. However, the inverse is not true. You cannot access instance variables in a static method. – CrimsonChris Jun 19 '14 at 15:05
  • You are the right teacher!These are the concepts i missed during my OOP .Can you share any sites,books where i learn everything from OOP. – dinesh Jun 19 '14 at 15:36
  • http://www.raywenderlich.com/45940/intro-object-oriented-design-part-1 – CrimsonChris Jun 19 '14 at 16:08

1 Answers1

3

Static variables are variables that are stored in what's called "static" storage which is allocated at application launch and exists for the lifetime of the application. In objective c, they are not part of the class, but their accessibility is scoped to where the variable is defined. Also, they differ from instance variables in that there is only one instance for your entire application, not one per object created.

Typically, a better way to define the singleton pattern in Objective-C is like so:

+ (instancetype)dKSingleInstance {
    static DKSingle* dKSingle;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dKSingle = [[DKSingle alloc]init];
    });
    return dKSingle;
}

This makes the static variable scoped to just the one method. Also, by using a dispatch_once, you offer some thread safety for initializing your static variable.

Sandy Chapman
  • 11,133
  • 3
  • 58
  • 67
  • 1
    Thanks for the answer sandy! But from learning of oops is that instance method cannot access static variable . In my example it happening and working also.Can you please help me from oop concept. – dinesh Jun 19 '14 at 14:42
  • Static variables are the opposite of OOP. OOP is set up to encapsulate data so that only an object can modify its state and those modifications occur by calling exposed methods. A static variable does not belong to any object. It belongs to the application. Many consider it an [anti-pattern](http://stackoverflow.com/q/12755539/1270148) for this reason. – Sandy Chapman Jun 19 '14 at 15:20