?
當實際上Singleton是一個對象,我們不能保證使用者不會使用其他的方法去創建(比如alloc),這個時候他就會創建多個實例,這樣就會出現這些無法感知的bug)
?
?
?
@implementation Singleton static Singleton * sharedSingleton = nil; + (Singleton *) sharedInstance { if (sharedSingleton == nil) { sharedSingleton = [[super allocWithZone:NULL] init]; } return sharedSingleton; } + (id) allocWithZone:(struct _NSZone *)zone { return [[self sharedInstance] retain]; } - (id) copyWithZone:(NSZone *) zone { return self; } - (id) retain { return self; } - (NSUInteger) retainCount { return NSUIntegerMax; } - (void) release { // } - (id) autorelease { return self; } @end
?