单例模式

单例模式
概念:在程序运行过程,一个类只有一个实例
作用:

①可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问

②从而方便地控制了实例个数,并节约系统资源

  使用场合

在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

举例说明:比如说登录控制器等等

ARC环境实现单例

#import "MSHPerson.h"

@implementation MSHPerson
定义一个静态变量保存对象,作用于是真个程序
static MSHPerson *_instance;

//重写该方法,保证永远都只分配一次空间
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
//    @synchronized(self) {
//        if (_instance == nil) {
//            _instance = [super allocWithZone:zone];
//        }
//    }
    
    //只会执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}
给外界提供一个share 也可以提供一个 defau开口的类方法 
+(instancetype)shareTools
{
    return [[self alloc]init];
}
这里要遵守协议<NSCoping,NSMUtableCoping>才可以敲出来给方法
-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}
@end

MRC环境实现单例

#import "XMGTools.h"

@implementation XMGTools

static XMGTools *_instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
//    if (_instance == nil) {
//        //线程2
//        //线程1
//        _instance = [super allocWithZone:zone];
//    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+(instancetype)shareTools
{
    return [[self alloc]init];
}

-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}
#pragma mark ----------------------
#pragma mark MRC

#if __has_feature(objc_arc)
    //ARC
#else
    //MRC
//什么都不做
-(oneway void)release
{
}

-(instancetype)retain
{
    return _instance;
}

-(NSUInteger)retainCount
{
    return MAXFLOAT;
}

#endif

单例模式通用宏

添加一个Single.h文件,将下面代码添加进去

#define SingleH(name) +(instancetype)share##name;

#if __has_feature(objc_arc)
//ARC
#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)share##name
{
return [[self alloc]init];
}

-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}
#else
//MRC
#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)share##name
{
return [[self alloc]init];
}

-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}
-(oneway void)release
{
}
-(instancetype)retain
{
    return _instance;
}

-(NSUInteger)retainCount
{
    return MAXFLOAT;
}
#endif
原文地址:https://www.cnblogs.com/mshong1616/p/5096498.html