1

I'd like to create a Singleton with ARC,
this is the answer I see.

Is there anyway to convert this code to something similar without using block?

+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

EDIT:

I just see this approach:

static MyClass *sharedMyClassInstance = nil; 

+(MyClass *) sharedMyClass
{
    @synchronized(self) {
        if (sharedMyClassInstance == nil) {
            sharedMyClassInstance = [[self alloc] init];
        }
        return sharedMyClassInstance;
    }
}

will this prevent the object created more than one?

Community
  • 1
  • 1
Tuyen Nguyen
  • 4,389
  • 7
  • 51
  • 77

2 Answers2

3

Yes, you can use another synchronization mechanism, like a mutex.

static MyClass *sharedInstance = nil;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static volatile BOOL initialized = NO;

pthread_mutex_lock(&mutex);

if ( ! initialized ) {
    initialized = YES;
    sharedInstance = [[MyClass alloc] init];
    // Do any other initialisation stuff here
}

pthread_mutex_unlock(&mutex);
return sharedInstance;
Nicolas Bachschmidt
  • 6,475
  • 2
  • 26
  • 36
  • Could you look at my EDIT, and see if that synchronization code works the same as yours. Thank you for you answer though. – Tuyen Nguyen Mar 21 '12 at 20:10
1

Is there anyway to convert this code to something similar without using block?

You can just go ahead and allocate your shared object, but then you don't get the protection that dispatch_once() offers. That function ensures that the block you give it runs no more than once during your app's execution. If the code that creates your singleton is inside the block you pass to dispatch_once(), you know that two threads in your app can't try to access the shared object at the same time and possibly cause it to be created twice.

Is there some reason you don't want to use a block?

Caleb
  • 124,013
  • 19
  • 183
  • 272