首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Objective-C 创设单例

2013-11-08 
Objective-C 创建单例程序开发(Objective-C)中,经常要用到单例,其创建代码如下:static Car *sharedInstanc

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

?说明:

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

?

热点排行