单例模式

作用:可以保证在程序运行过程中,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约了系统资源

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;\
}\
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章