單例模式

作用:可以保證在程序運行過程中,一個類只有一個實例,而且該實例易於供外界訪問,從而方便地控制了實例個數,並節約了系統資源

ARC和非ARC模式下實現

ARC模式下實現單例模式

//關鍵在於只分配一塊存儲空間

@implementation Person

static Person *_instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone{

  @synchronized(self){
       if(_instance == nil){
          _instance = [super allocWithZone:zone]
        }
       return _instance;
   } 
}
@interface Person() <NSCopy, NSMutableCopy>
@end
@implementation Person

static Person *_instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       _instance = [super allocWithZone:zone];
    })
    
    return _instance;
}

+(instancetype)sharedPerson{
     return [[Person alloc] init];
}

-(id)copyWithZone:(NSZone *)zone{
//對象方法,說明在調用該方法之前已經存在對象了
     return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
     return _instance;
}

MRC模式下實現單例模式

單例模式:在整個程序運行過程中,對象都不會被釋放

@interface Person() <NSCopy, NSMutableCopy>
@end
@implementation Person

static Person *_instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       _instance = [super allocWithZone:zone];
    })
    
    return _instance;
}

+(instancetype)sharedPerson{
     return [[Person alloc] init];
}

-(id)copyWithZone:(NSZone *)zone{
//對象方法,說明在調用該方法之前已經存在對象了
     return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
     return _instance;
}
#if __has_feature(objc_arc)
//條件滿足 ARC


#else
//MRC
-(oneway void)release{
    
}
-(instancetype)retain{
   return _instance;
}
-(NSUInteger)retainCount{
   return MAXFLOAT;
}
#endif

單例模式通用宏

//帶參數的宏 用傳進來的name替換代碼中的name
#define SingleH(name) +(instancetype)share##name;
#define SingleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
    
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
       _instance = [super allocWithZone:zone];\
    })\
    
    return _instance;\
}\
+(instancetype)shared##name{\
     return [[Person alloc] init];\
}\
-(id)copyWithZone:(NSZone *)zone{\
//對象方法,說明在調用該方法之前已經存在對象了\
     return _instance;\
}\
-(id)mutableCopyWithZone:(NSZone *)zone{\
     return _instance;\
}\
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章