单例--只写一次就够了

2017-04-19  本文已影响0人  maybenai

单例简介

1、可以确保程序在运行过程中,一个类只有一个实例,而且该实例易于提供外接访问从而方便的控制了实例的个数,节约资源

2、在整个应用程序中,共享一份资源,一般用于工具类

3、优缺点:
优点:对需要的对象只创建一次,节约资源
缺点:a. 单例对象指针存放在静态区的,单例对象在堆中分配的内存空间,会在应用程序终止后才会被释放。
b.单例类无法继承,因此很难进行类扩展
c.单例不适用于变化的对象

实现

#import "KCShareInstance.h"

static KCShareInstance * shareInstance = nil;

@implementation KCShareInstance

//在该方法中初始化要保存的对象
- (instancetype)init
{
    if (self = [super init]) {
    }
    return self;
}

//初始化单例对象
+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        shareInstance = [[[self class] alloc] init];
        
    });

    return shareInstance;
}


//保证单例只分配一个内存地址
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [super allocWithZone:zone];
        
    });
    
    return shareInstance;
}

在pch文件中初始化单例

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

#if __has_feature(objc_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
#define singleM static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)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;\
}\
-(oneway void)release\
{\
}\
\
-(instancetype)retain\
{\
    return _instance;\
}\
\
-(NSUInteger)retainCount\
{\
    return MAXFLOAT;\
}
#endif

这时我们就可以在任何项目中,当我们要使用单例类的时候只要在项目中导入PCH文件然后
在.h文件中调用singleH(类名)
在.m文件中调用singleM(类名)
创建类时直接调用share类名方法即可。

上一篇 下一篇

猜你喜欢

热点阅读