您的位置:首页 > 移动开发 > IOS开发

iOS中类单例方法的一种实现

2015-11-13 16:05 274 查看
在Cocos2D编程中,很多情况我们需要类只生成一个实例,这称之为该类的单例类.

一般我们在类中这样实现单例方法:

+(instancetype)sharedInstance{
static Foo *sharedInstance;
if(!sharedInstance){
sharedInstance = [Foo new];
}
return sharedInstance;
}


注意静态变量sharedInstance也可以放到类外部去.

但是如果是多线程环境中,上述方法并不能一定保证生成唯一实例,你还必须添加同步代码.

一不小心,你写的同步代码有可能就是错的.如果是简单的Cocos2D单线程程序很可能发现不了,如果放到复杂的多线程App中运行可能就会出现莫名其妙的错误.

殊不知Foundation平台中已经提供了简单的解决办法,我们可以这样写:

+(instancetype)sharedInstance{
static dispatch_once_t once;
static Foo *sharedInstance;
dispatch_once(&once,^{
sharedInstance = [self new];
});
return sharedInstance;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS foundation 单例