在引入 instance 后,我正在研究现代的 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]? 给出的答案与本题无关
Best Answer-推荐答案 strong>
在这种情况下,使用 [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/
|