单例的实现

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

附:


单例的实现_第1张图片
单例的实现_第2张图片
单例的实现_第3张图片

你可能感兴趣的:(单例的实现)