单例模式算是开发中比较常见的一种模式了。在iOS中,单例有两种实现方式(至少我目前只发现两种)。

根据线程安全的实现来区分,一种是使用@synchronized ,另一种是使用GCD的dispatch_once函数。

 

1.@synchronized 实现

static InstanceClass *instance;
+ (InstanceClass *)defaultInstance{
    @synchronized (self){
        if (instance == nil) {
            instance = [[InstanceClass alloc] init];
        }
    }
    
    return instance;
}

 

2.GCD的dispatch_once

static InstanceClass *instance;
+ (InstanceClass *)defaultInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[InstanceClass alloc] init];
    });
    
    return instance;}

 

posted on 2015-05-29 15:44  android 勤奋  阅读(386)  评论(0)    收藏  举报