单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
#import <Foundation/Foundation.h> @interface Singleton : NSObject +(Singleton *) instance;
@end @implementation Singleton
+(Singleton *) instance { static Singleton *sharedSingleton_ = nil; @synchronized(self){ if(sharedSingleton_ == nil){ sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init]; } } return sharedSingleton_; } + (id) allocWithZone:(NSZone *)zone { return [[self sharedInstance] retain]; } - (id) copyWithZone:(NSZone*)zone { return self; } - (id) retain { return self; } - (NSUInteger) retainCount { return NSUIntegerMax; } -(void)release { [super release]; } - (id) autorelease { return self; } @end
当然,ios 5以上启用ARC就简单多了:
static RootViewController* sharedRootController = nil; +(RootViewController *) sharedController{ @synchronized(self){ if (sharedRootController == nil) { sharedRootController = [[self alloc] init]; } } return singleController; }