iOS 單例模式(Singleton)
- 故名思議 ,單例, 即是在整個(gè)項(xiàng)目中,這個(gè)類的對(duì)象只能被初始化一次。
- 直接上代碼 - - ARC中單例模式的實(shí)現(xiàn)
.h文件
#import <Foundation/Foundation.h>
@interface MySingle : NSObject
+(instancetype)sharedFoot;
@end
.m文件
步驟:
1.一個(gè)靜態(tài)變量 _inastance
2.重寫allocWithZone,在里面用dispatch_once,并調(diào)用super allcoWithZone
3.自定義一個(gè)sharedXX , 用來(lái)獲取大力,在里面也可調(diào)用 dispatch_once ,直接返回 _instance即可
#import "MySingle.h"
@implementation MyDingle
static MySingle *_instance;//第一步 儲(chǔ)存唯一的實(shí)例
第二歩 分配內(nèi)存都會(huì)調(diào)用這個(gè)方法, 保證分貝內(nèi)存alloc時(shí)都相同
調(diào)用dispatch_once 保證在多線程中也被實(shí)例化一次
+(id )allocWIthZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken ,^{
_instance = [super allocWithZone:zone];
?);
第三歩:保證init初始化時(shí)都相同
+(instancetype)sharedFoot{
static dispatch_once_t onceToken;
dispatch_once(&onceToken ,^{
_instance = [[MySingle alloc]init];
});
return _instance;
}
第四步: 保證copy 時(shí)都相同
-(id)copyWirhZone:(NSZone *)zone{
return _instance;
}
在需要的地方調(diào)用 這樣單例就創(chuàng)建完成
MySingle *one = [[MySingle alloc]init];
轉(zhuǎn)自 http://www.itdecent.cn/users/b9479de9c9bb/latest_articles