單例模式須要達到的目的app
1. 封裝一個共享的資源ui
2. 提供一個固定的實例建立方法spa
3. 提供一個標準的實例訪問接口.net
在iOS中有不少單例對象,好比UIApplication,UIScreen等等。code
//.h文件 #import <Foundation/Foundation.h> @interface Singleton : NSObject //單例方法 +(instancetype)sharedSingleton; @end //.m文件 #import "Singleton.h" @implementation Singleton //全局變量 static id _instance = nil; //單例方法 +(instancetype)sharedSingleton{ return [[self alloc] init]; } ////alloc會調用allocWithZone: +(instancetype)allocWithZone:(struct _NSZone *)zone{ //只進行一次 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } //初始化方法 - (instancetype)init{ // 只進行一次 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super init]; }); return _instance; } //copy在底層 會調用copyWithZone: - (id)copyWithZone:(NSZone *)zone{ return _instance; } + (id)copyWithZone:(struct _NSZone *)zone{ return _instance; } + (id)mutableCopyWithZone:(struct _NSZone *)zone{ return _instance; } - (id)mutableCopyWithZone:(NSZone *)zone{ return _instance; } @end
單例模式使用對象
[plain blog
[[SingletonClass sharedInstance] xxx]; 接口
單例的銷燬資源
銷燬也就是對單例的釋放,在應用終止的時候實現,delegate方法以下。get
[plain]
- (void)applicationWillTerminate:(UIApplication *)application
{
[SingletonClass destroyDealloc];
}
銷燬方法
[plain]
+ (void)destroyDealloc
{
if ([getInstance retainCount] != 1)
return;
[getInstance release];
getInstance = nil;
}
(重點)另一種單例的建立:http://blog.csdn.net/lovefqing/article/details/8516536