@implementation MySingletonClass
static MySingletonClass *sharedInstance = nil;
+ (MySingletonClass*)sharedInstance {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
}
+ (id)alloc {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super alloc];
return sharedInstance;
}
}
return nil;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance;
}
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
return self;
}
@end
Vous ne savez pas si vous pouvez remplacer à la fois alloc et allocWithZone: comme ceci ...?Est-ce que ce motif singleton a du sens?
+1 pour le modèle de Matt, ce qui économise tout le travail. –