`
wangleyiang
  • 浏览: 214882 次
社区版块
存档分类
最新评论

Objective-C 创建单例

阅读更多

程序开发(Objective-C)中,经常要用到单例,其创建代码如下:

static Car *sharedInstance = nil;

#pragma mark Single instance
+ (Car *)sharedInstance {
    if (!sharedInstance) {
        sharedInstance = [[self alloc] init];
    }
    return sharedInstance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [super allocWithZone:zone];
            return sharedInstance;
        }
    }
    return nil;
}

 说明:

  1. 覆盖allocWithZone:方法的目的是为了防止任何类创建第二个实例;
  2. @synchronized指令防止多线程同时调用该代码块;

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics