+ (GrabClass *)grab{
static GrabClass * ngrab = nil;
if (ngrab==nil)
{
ngrab=[[GrabClass alloc]init];
}
return grab;
}
J'ai utilisé beaucoup de singletons dans mon programme. Si je le fais comme ça, il y a cependant une chance que la méthode grab soit appelée par différents threads en même temps.
Comment l'éviter?
Ma solution actuelle est de faire:
+ (GrabClass *)grab{
static GrabClass * ngrab = nil;
[Tools DoSomethingWithSynchronize:^{
if (ngrab==nil)
{
ngrab=[[GrabClass alloc]init];
}
}];
return grab;
}
Où
+(void)DoSomethingWithSynchronize:(void (^)())block
{
@synchronized (self)
{
[self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=[NSThread currentThread];
[self breakIfLock]; //should not be called
block();
[self singleton].lockToMakeSureThatOnlyOneThreadAccessThis=nil;
}
}
Cela ressemble à de l'overkill. Je me demande s’il existe une meilleure solution standard
Réponses:
1 pour la réponse № 1Vous pourriez obtenir un très bon exemple et de la documentation ici.
Vous pouvez simplement utiliser @synchronized(self)
pour synchroniser les opérations.