美文网首页
单例的实现

单例的实现

作者: March_Cullen | 来源:发表于2017-03-02 21:31 被阅读0次

    一、使用GCD实现

    // .h文件
    #define LYSingletonH + (instance)sharedInstance;
    // .m文件
    #define LYSingletonM \
    static id _instance; \
    \
    + (instancetype)allocWithZone:(struct _NSZone *)zone \
    { \
            static dispatch_once_t onceToken; \
            dispatch_once(&onceToken, ^{ \
                     _instance = [super allocWithZone:zone] \
            }); \
            return _instance; \
    } \
    \
    + (instancetype)sharedInstance \
    { \
            static dispatch_once_t onceToken; \
            dispatch_once(&onceToken, ^{ \
                    _instance = [super allocWithZone:zone]; \
            }); \
            return _instance; \
    } \
     \
    - (id)copyWithZone:(NSZone *)zone \
    { \
            return _instance; \
    }
    

    二、加锁实现

    static id _instance;
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
            @synchronized(self) {
                    if (_instance == nil) {
                            _instance = [super allocWithZone:zone];
                    }
            }
            return _instance;
    }
    + (instancetype)sharedInstance
    {
            @synchronized(self) {
                    if (_instance == nil) {
                            _instance = [super allocWithZone:zone];
                    }
            }
            return _instance;
    }
    - (id)copyWithZone:(NSZone *)zone
    {
            return _instance;
    }
    

    附:


    相关文章

      网友评论

          本文标题:单例的实现

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