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.
来源:https://www.cnblogs.com/whyandinside/p/3300795.html