iOS单例模式

2016-07-02  本文已影响32人  _叫我小贱

方法1:GCD方式实现

1.allocwithzone方法的重写

static Person *_person;

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

2.实现单例的shared方法

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

3.重写copy方法

@interface Person() <NSCopying>

@end

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

方法二:加锁实现

1.allocwithzone方法的重写

static Person *_person;

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

2.实现单例的shared方法

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

3.重写copy方法

@interface Person() <NSCopying>

@end

- (id)copyWithZone:(NSZone *)zone
{
    return _person;
}
上一篇 下一篇

猜你喜欢

热点阅读