在Objective-C中使用GCD的dispatch_once创建单例 [英] Create singleton using GCD's dispatch_once in Objective-C
本文介绍了在Objective-C中使用GCD的dispatch_once创建单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您可以定位到iOS 4.0或更高版本
If you can target iOS 4.0 or above
使用GCD,这是在Objective-C(线程安全)中创建单例的最佳方法吗?
Using GCD, is it the best way to create singleton in Objective-C (thread safe)?
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
推荐答案
这是创建类实例的一种完全可接受且线程安全的方法.从技术上讲,它可能不是一个单个"(因为这些对象只能有1个),但是只要您仅使用[Foo sharedFoo]
方法访问该对象,就足够了.
This is a perfectly acceptable and thread-safe way to create an instance of your class. It may not technically be a "singleton" (in that there can only ever be 1 of these objects), but as long as you only use the [Foo sharedFoo]
method to access the object, this is good enough.
这篇关于在Objective-C中使用GCD的dispatch_once创建单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文