1

I am used to Java and currently on the process of learning Objective-C.

Basically I would create Singleton classes in Java like this:

public class SingletonClass{
  private static instance; //Step 1

  public static SingletonClass getInstance(){ //Step 2
    if(instance == null)
      instance = new SingletonClass();

    return instance;
  }
} 

Very straightforward right?

But I find a hard time creating straight forward solution for that in Objective-C

I did like this:

@implementation SingletonClass(){
  //I want to do step 1 here which is to make a private static instance;
  //it is said that private variables are declared here
  static SingletonClass *instance; //but it is said that static keyword is different here
}

//then I would do something like step 2
+ (id)getInstance{
  if(instance == nil)
    instance = self;

  return instance;
}

@end

The problem is that there is an error :Type name does not allow storage class to be specified

How do you guys make straight forward Singleton classes in Objective-C?

Rick Royd Aban
  • 904
  • 6
  • 33

2 Answers2

1

Use dispatch_once_t:

From Apple docs dispatch_once(3)
The dispatch_once() function provides a simple and efficient mechanism to run an initializer exactly once, similar to pthread_once(3).

Also see: Secrets of dispatch_once by Mike Ash

+(instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SingletonClass alloc] init];
    });
    return sharedInstance;
}
zaph
  • 111,848
  • 21
  • 189
  • 228
-3

They are called external variables in objective c.

In app delegate under #import put

NSString *singleton;

Then in what ever class (view controller) you want to use it in's .h file

extern NSString *singleton;
Tom Testicool
  • 563
  • 7
  • 26