[iOS dispatch_once创建单例]

自苹果引入了Grand Central Dispatch (GCD)(Mac OS 10.6和iOS4.0)后,创建单例又有了新的方法,那就是使用dispatch_once函数,当然,随着演进的进行,还会有更多的更好的方法出现。

我们先看下函数void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);其中第一个参数predicate,该参数是检查后面第二个参数所代表的代码块是否被调用的谓词,第二个参数则是在整个应用程序中只会被调用一次的代码块。dispach_once函数中的代码块只会被执行一次,而且还是线程安全的。

+(SchoolManager *)sharedInstance  
{  
    static SchoolManager *sharedManager;  
      
    static dispatch_once_t onceToken;  
    dispatch_once(&onceToken, ^{  
        sharedManager = [[SchoolManager alloc] init];  
    });  
      
    return sharedManager;  
}  

引用自:http://blog.csdn.net/ryantang03/article/details/8622415

原文地址:https://www.cnblogs.com/rayshen/p/4499864.html