Reputation: 4479
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?
Upvotes: 1
Views: 668
Reputation: 124997
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?
Upvotes: 1
Reputation: 6505
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;
Upvotes: 3