ITselector首页投稿(暂停使用,暂停投稿)

iOS 单例(singleton,GCD,@synchroniz

2016-05-18  本文已影响425人  不误正业的开发者

iOS中单例模式的两种创建方法:GCD 和 @synchronize

1.GCD的方法

@interface JYPerson () //<NSCopying>

@end

@implementation JYPerson

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 = [[self alloc] init];
        }
    }
    return _instance;
}

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


2.GCD方法的宏实现

// .h文件
#define JYSingletonH + (instancetype)sharedInstance;

// .m文件
#define JYSingletonM \
\
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 = [[self alloc] init];\
    });\
    return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
    \
    return _instance;\
}

// .h文件
#define JYSingletonH(name) + (instancetype)shared##name;

// .m文件
#define JYSingletonM(name) \
static id _instance; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}

3.传统写法:

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

+ (instancetype)sharedInstance {
    @synchronized (self) {
        if (_instance == nil) {
            
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

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

4.注意事项:

NSLog(@"%@ %@", [JYStudent sharedInstance], [[JYStudent alloc] init]);
NSLog(@"%@ %@", [JYTeacher sharedInstance], [[JYTeacher alloc] init]);
上一篇下一篇

猜你喜欢

热点阅读