怎样实现一个singleton的类

来源:互联网 发布:我的世界枪械js下载 编辑:程序博客网 时间:2024/06/05 01:07

static LOSingleton * shareInstance;

+( LOSingleton *)sharedInstance{

    @synchronized(self){//这个东西其实就是一个加锁。如果self其他线程访问,则会阻塞。这样做一般是用来对单例进行一个死锁的保护

        if (shareInstance == nil) {

            shareInstance = [[super allocWithZone:NULL] init];

        }

    }

return shareInstance;

}


//第二种方式

+ (LOSingleton *) sharedInstance

{

    static  LOSingleton *sharedInstance = nil ;

    static  dispatch_once_t onceToken;  //

    dispatch_once (& onceToken, ^ {     //最多调用一次

        sharedInstance = [[self  alloc] init];

    });

    return  sharedInstance;

}

0 0