单列

2017-03-30  本文已影响0人  AntKing

OC中使用单列

在多线程的使用的环境中,要设置线程锁,否则得到就不是同一个单列,而会创建另一个单列

static PayManager *_instance = nil;


/**
 * 实例化类
 */
+(instancetype)sharedMusicTool{
    if (_instance == nil) {//防止频繁枷锁
        @synchronized(self) {
            if (_instance == nil) {//防止创建多次
                _instance = [[self alloc] init ];
            }
        }
    }
    return _instance;
}
 
/**
 * 重写copy方法,保证copy出来的也是单例类
 */
-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}


/**
 * alloc 方法内部会调用这个方法
 */
+(id)allocWithZone:(struct _NSZone *)zone{
    if (_instance == nil) {//防止频繁加锁
        @synchronized(self) {
            if (_instance == nil) {//防止创建多次
                _instance = [super allocWithZone:zone];
            }
        }
    }
    return _instance;
}
 
上一篇下一篇

猜你喜欢

热点阅读