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?
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 todispatch_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?