为什么Apple建议使用dispatch_once在ARC下实现单例模式? [英] Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC?
问题描述
在ARC下的单例的共享实例访问器中使用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
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
在后台异步实例化单例不是一个坏主意吗?我的意思是如果我请求共享实例并立即依赖它会发生什么,但dispatch_once要到圣诞节才能创建我的对象?它不会马上回来吗?至少这似乎是Grand Central Dispatch的重点。
Isn't it a bad idea to instantiate the singleton asynchronously in the background? I mean what happens if I request that shared instance and rely on it immediately, but dispatch_once takes until Christmas to create my object? It doesn't return immediately right? At least that seems to be the whole point of Grand Central Dispatch.
那他们为什么这样做?
推荐答案
dispatch_once()
绝对是同步的。并非所有GCD方法都异步执行(例如, dispatch_sync()
是同步的)。使用 dispatch_once()
取代以下习语:
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 {
static MyClass *sharedInstance;
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[MyClass alloc] init];
}
}
return sharedInstance;
}
dispatch_once()$ c的好处$ c>这是因为它更快。它在语义上也更清晰,因为它还可以保护您免受多个线程的影响,这些线程执行您的sharedInstance的alloc init - 如果它们都在相同的时间尝试。它不允许创建两个实例。
dispatch_once()
的整个想法是只执行一次,这正是我们正在做的事情。
The benefit of dispatch_once()
over this is that it's faster. It's also semantically cleaner, because it also protects you from multiple threads doing alloc init of your sharedInstance--if they all try at the same exact time. It won't allow two instances to be created. The entire idea of dispatch_once()
is "perform something once and only once", which is precisely what we're doing.
这篇关于为什么Apple建议使用dispatch_once在ARC下实现单例模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!