在引入实例
之后,我正在研究 Objective-C 的现代模式来创建单例
来自:Create singleton using GCD's dispatch_once in Objective C
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = [self new];
});
return sharedInstance;
}
我想知道为什么不使用 [MyFunnyClass new] 如下?
@implementation MyFunnyClass
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = [MyFunnyClass new];
});
return sharedInstance;
}
或者是否相同?
(引用:http://nshipster.com/instancetype/)
编辑:Why use [ClassName alloc] instead of [[self class] alloc]?给出的答案与此问题无关
最佳答案
在本例中,使用 [self new]
而不是 [MyClass new]
并使用 static id sharedInstance
的原因而不是 static MyClass *sharedInstance
,是因为您只需复制并粘贴整个方法而无需编辑它。该方法中没有任何内容特定于它所属的类。
关于ios - Objective-C 单例 GCD - [self alloc] 或 [Class alloc],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851847/