单例模式之懒汉模式(GCD实现)

HMDataTool.h

#import <Foundation/Foundation.h>

@interface HMDataTool : NSObject
+ (instancetype)sharedDataTool;
@end

HMDataTool.m

#import "HMDataTool.h"

@implementation HMDataTool
// 用来保存唯一的单例对象
static id _instace;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super allocWithZone:zone];
    });
    return _instace;
}

+ (instancetype)sharedDataTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] init];
    });
    
    return _instace;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instace;
}

@end

 

posted @ 2015-11-20 15:02  Z了个L  阅读(125)  评论(0编辑  收藏  举报