单例的两种创建方式

来源:互联网 发布:乐视电视切换网络电视 编辑:程序博客网 时间:2024/06/10 05:14

第一种方法:

static MainViewController *shareInstance;+ (MainViewController *)sharedInstance{    @synchronized (self) {        if (nil == shareInstance) {            shareInstance = [[super allocWithZone:NULL] init];        }    }    return shareInstance;}

第二种方法:

+ (MainViewController *)sharedInstance{    static MainViewController *sharedInstance = nil;    static dispatch_once_t onceToken;   // 锁        dispatch_once(&onceToken, ^{        sharedInstance = [[self alloc] init];    });        return sharedInstance;}


0 0