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

时间:2023-03-09 01:41:41
iOS中类单例方法的一种实现

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