单例的实现

2017-03-02  本文已影响0人  March_Cullen

一、使用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;
}

附:


上一篇 下一篇

猜你喜欢

热点阅读