Objective-C 单例 GCD - [self alloc] 或 [Class alloc]
Objective-C singleton GCD - [self alloc] or [Class alloc]
在引入 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]? 处给出的答案与此问题无关
见Why use [ClassName alloc] instead of [[self class] alloc]?
另外,惯例是使用alloc/init,不是新的。参见 alloc, init, and new in Objective-C
在这种情况下,使用 [self new]
而不是 [MyClass new]
并使用 static id sharedInstance
而不是 static MyClass *sharedInstance
的原因是因为您可以只复制和粘贴整个方法而不对其进行编辑。该方法中的任何内容都不是特定于它所属的 class。
在引入 instance
来自: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]? 处给出的答案与此问题无关
见Why use [ClassName alloc] instead of [[self class] alloc]?
另外,惯例是使用alloc/init,不是新的。参见 alloc, init, and new in Objective-C
在这种情况下,使用 [self new]
而不是 [MyClass new]
并使用 static id sharedInstance
而不是 static MyClass *sharedInstance
的原因是因为您可以只复制和粘贴整个方法而不对其进行编辑。该方法中的任何内容都不是特定于它所属的 class。