Creating an instance of the Singleton class

I created a singleton class to track my data in my iPhone application. I know that singleton needs to be created only once, but what is the best place to create it? Should this be done in appDelegate? I want to be able to call this singleton (which contains NSMutableArray) from many classes so that I can access the array.

Here is my class that I wrote:

#import "WorkoutManager.h"

static WorkoutManager *workoutManagerInstance;

@implementation WorkoutManager
@synthesize workouts;

+(WorkoutManager*)sharedInstance {
    if(!workoutManagerInstance) {
        workoutManagerInstance = [[WorkoutManager alloc] init];
    }
    return workoutManagerInstance;
}

-(id)init {
    self = [super init];
    if (self) {
        workouts = [[NSMutableArray alloc] init];
    }
    return self;
}

@end
+3
source share
5 answers

- , . , [Something sharedSomething], . , " Objective-C, ARC?" .

+6

- . .

: 1. - (.. dispatch_once()). 2. , . 3. , . 4. ( ). 5. .

, - . +load , , . (+initialize , - , () ( +load), , ' sharedInstance.)

gcc __constructor__ ( clang), , ObjC. main(). , . , .

+2

, , :

static MyClass* theInstance = nil;

+ (MyClass*) sharedInstance {
    @synchronized(self) {
        if (! theInstance) {
            theInstance = [[MyClass alloc] init];
        }
    }

    return theInstance;
}

... , , [MyClass sharedInstance], .

, , alloc init . , init , , / alloc init.

In practice, however, singleton classes most often use the approach sharedInstance(sometimes with minor variations in the name, for example [UIApplication sharedApplication]).

+1
source

Usually, when you create the first instance of singleton classes, the first time is created:

static SomeClass *_instance = nil;

+ (SomeClass *) instance {
    @synchronized(self) {
        if (!_instance)
            _instance = [[self alloc] init];
    }
    return _instance;
}
0
source

I use this code to create singleton. GCD takes care of synchronization

+ (SingletonClass *)sharedInstance {
  static SingletonClass *sharedInstance;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[SingletonClass alloc] init];
    sharedInstance.property = [Property new];
  });
  return sharedInstance;
}
0
source

All Articles