单列

作者: AntKing | 来源:发表于2017-03-30 21:45 被阅读0次

    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;
    }
     
    

    相关文章

      网友评论

          本文标题:单列

          本文链接:https://www.haomeiwen.com/subject/huapottx.html