Pro*_*ber 303 singleton objective-c ios automatic-ref-counting
在ARC下的单例的共享实例访问器中使用dispatch_once的确切原因是什么?
+ (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;
}
Run Code Online (Sandbox Code Playgroud)
在后台异步实例化单例不是一个坏主意吗?我的意思是如果我请求共享实例并立即依赖它会发生什么,但dispatch_once要到圣诞节才能创建我的对象?它不会马上回来吗?至少这似乎是Grand Central Dispatch的重点.
那他们为什么要这样做呢?
Lil*_*ard 416
dispatch_once()
是完全同步的.并非所有GCD方法都异步执行(例如,dispatch_sync()
同步).使用dispatch_once()
取代以下习语:
+ (MyClass *)sharedInstance {
static MyClass *sharedInstance;
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[MyClass alloc] init];
}
}
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
相比之下的好处dispatch_once()
是它更快.它在语义上也更清晰,因为它还可以保护您免受多个线程的影响,这些线程执行sharedInstance的alloc init - 如果它们都在相同的时间尝试.它不允许创建两个实例.整个想法dispatch_once()
是"只执行一次",这正是我们正在做的事情.
Abi*_*ern 41
因为它只运行一次.因此,如果您尝试从不同的线程访问它两次,它将不会导致问题.
Mike Ash在他的Care and Feeding of Singletons博客文章中有完整的描述.
并非所有GCD块都是异步运行的.
归档时间: |
|
查看次数: |
75149 次 |
最近记录: |