+ (GrabClass *)grab{
static GrabClass * ngrab = nil;
if (ngrab==nil)
{
ngrab=[[GrabClass alloc]init];
}
return grab;
}
I used many singletons in my program. If I do it like that, however there is a chance that the grab method is called by different threads at the same time.
How to avoid it?
My current solution is to do:
+ (GrabClass *)grab{
static GrabClass * ngrab = nil;
[Tools DoSomethingWithSynchronize:^{
if (ngrab==nil)
{
ngrab=[[GrabClass alloc]init];
}
}];
return grab;
}
Where
+(void)DoSomethingWithSynchronize:(void (^)())block
{
@synchronized (self)
{
[self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=[NSThread currentThread];
[self breakIfLock]; //should not be called
block();
[self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=nil;
}
}
Seems like overkill. I wonder if there's a better standard solution