Grand Central Dispatch (GCD)

此生再无相见时 提交于 2020-04-03 05:30:38

1. 关于 dispatch_once

dispatch_once

Executes a block object once and only once for the lifetime of an application.
在stackoverflow上有个对dispatch_once的解释,非常棒:

What's the exact reason for using dispatch_once in the shared instance accessor of a singleton under ARC?

+(MyClass*)sharedInstance
{
//  Static local predicate must be initialized to 0
    staticMyClass*sharedInstance = nil;
    staticdispatch_once_t onceToken =0;
    dispatch_once(&onceToken,^{
        sharedInstance =[[MyClass alloc] init];
    // Do any other initialisation stuff here
    });
    return sharedInstance;
}   

dispatch_once() is absolutely synchronous. Not all GCD methods do things asynchronously (case in point, dispatch_sync() is synchronous). The use of dispatch_once() replaces the following idiom:

+(MyClass*)sharedInstance {
    staticMyClass*sharedInstance;
    @synchronized(self)
    {
        if(sharedInstance == nil)
        {
            sharedInstance =[[MyClass alloc] init];
        }
    }
    return sharedInstance;
} 

The benefit of dispatch_once() over this is that it's faster. It's also semantically cleaner, because the entire idea of dispatch_once() is "perform something once and only once", which is precisely what we're doing.

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!