I’ve found this snippet of code on the net. It sets up an NSMutableArray in a way I’ve not seen before ( I’m an Obj-C newb). Can someone explain what it’s doing and why you would do it this way? Particularly the @syncronized, static and little plus sign on the method signature.
add the following to the .h file:
+(NSMutableArray *)allMySprites;
add the following to he .m file after implementation:
static NSMutableArray * allMySprites = nil;
+(NSMutableArray *)allMySprites {
@synchronized(allMySprites) {
if (allMySprites == nil)
allMySprites = [[NSMutableArray alloc] init];
return allMySprites;
}
return nil;
}
Adding to the other responses … the posted code is wrong. It should be more like this:
It makes no sense to @synchronize on nil. Using self in a class method refers to the class and not the instance. Also the ‘return nil’ in the original code is pointless.
A better approach where the @synchronized can be completely avoided is to use a class initializer method:
The initialize methods are guaranteed to be called before the class is used.