@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
不知道是否可以覆盖alloc和allocWithZone:像这样...?这个单身模式有意义吗?
+1为Matt的模板,它可以保存所有的工作。 – 2010-12-15 14:17:13