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.

3
  • You can use static variables in instance methods. However, the inverse is not true. You cannot access instance variables in a static method. Commented Jun 19, 2014 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. Commented Jun 19, 2014 at 15:36
  • raywenderlich.com/45940/intro-object-oriented-design-part-1 Commented Jun 19, 2014 at 16:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 for this reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.