-2

Whats the best pattern for singleton? I frequently use

+ (SomeManager *)shared
{
    static SomeManager * _SomeManager = nil;
    if (_SomeManager) {
        return _SomeManager;
    }

    _SomeManager = [[SomeManager alloc] init];

    return _SomeManager;
}

Is this thread safe? If not, hot to make it safe?

Cezar
  • 55,636
  • 19
  • 86
  • 87
Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179
  • 1
    See http://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c – Guillaume Algis Jul 27 '13 at 12:28
  • `NSLock` or `@synchronized` or `dispatch_once` or etc... – holex Jul 27 '13 at 12:45
  • Keep in mind that "singleton" and "thread-safe object" are two *entirely* different things. – Hot Licks Jul 27 '13 at 13:37
  • 1
    Lazy allocation of singletons, which usually represent a handful of bytes of memory, is a degenerate pattern. Allocate your singleton in +[SomeManger initialize], guaranteed to only be called once at class load time. – Bored Astronaut Jul 27 '13 at 15:59

2 Answers2

1

Using an example from Create singleton using GCD's dispatch_once in Objective C

+ (id)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

Clear and simple. Google better next time.

Community
  • 1
  • 1
Mehdzor
  • 789
  • 4
  • 9
  • 23
0

I prefer to use the GCD dispatch_once method...

+ (id) sharedSomethingManager
{
    static dispatch_once_t onceQueue;
    static SomethingkManager *somethingManager = nil;

    dispatch_once(&onceQueue, ^{somethingManager = [[self alloc] init]; });
    return somethingManager;
}
Nick Banks
  • 111
  • 2