单例-Singleton-02

.h文件

#import <Foundation/Foundation.h>

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

.m文件

#import "HMDataTool.h"

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

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

+ (instancetype)sharedDataTool
{
    // 线程安全的
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

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

@end

 

posted on 2015-03-16 17:52  FKunLam  阅读(86)  评论(0编辑  收藏  举报