如果你可以针对 iOS 4.0 或更高版本
使用 GCD,在 Objective-C(线程安全)中创建单例是最好的方法吗?
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
最佳答案
这是创建类实例的完全可接受且线程安全的方法。从技术上讲,它可能不是“单例”(因为这些对象只能有 1 个),但只要您只使用 [Foo sharedFoo]
方法来访问该对象,这就是足够好。
https://stackoverflow.com/questions/5720029/