美文网首页iOS科普小讲堂
OC创建一个严谨的单例类

OC创建一个严谨的单例类

作者: 执笔时光er | 来源:发表于2020-04-01 11:10 被阅读0次

    单例:顾名思义,内存中只有单独一份的实例。
    要实现严谨的真正意义的上的单例,就要把所有的创建对象的方式都统一管理起来,只返回内存中唯一的位置,代码如下:

    @interface CQSQLiteUtil : NSObject
    //提供的唯一创建接口
    +(instancetype)shareInstance;
    @end
    
    #import "CQSQLiteUtil.h"
    //内存中的唯一对象
    static CQSQLiteUtil * _instance;
    //接受Copy协议和MutableCopy协议,管理copy和mutableCopy
    @interface CQSQLiteUtil ()<NSCopying,NSMutableCopying>
    @end
    @implementation CQSQLiteUtil
    
    +(instancetype)shareInstance{
        return [[self alloc]init];
    }
    
    //当调用alloc的时候会调用allocWithZone
    +(instancetype)allocWithZone:(struct _NSZone *)zone{
        //在alloc的总接口限制创建的操作
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    //限制Copy操作创建的对象
    - (nonnull id)copyWithZone:(nullable NSZone *)zone {
        return _instance;
    }
    //限制MutableCopy操作创建的对象
    - (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {
        return _instance;
    }
    @end
    

    另外,再附记一个单例类的宏定义

    //.h定义替换
    #define SingletonH(name) +(instancetype)share##name;
    
    //.m定义替换
    #define SingletonM(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;\
    }
    

    这里有两个宏定义,分别是在.h文件和.m文件进行使用替换的。

    我曾执笔雕刻时光,奈何良辰难书过往。

    相关文章

      网友评论

        本文标题:OC创建一个严谨的单例类

        本文链接:https://www.haomeiwen.com/subject/gdeouhtx.html