Object-C单例
+ (instancetype)sharedInstance {
static Kraken *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Kraken alloc] init];
});
return sharedInstance;
}Swift单例
class TheOneAndOnlyKraken {
static let sharedInstance = TheOneAndOnlyKraken()
private init() {} //This prevents others from using the default '()' initializer for this class.
}
本文介绍了Objective-C和Swift两种编程语言中实现单例模式的方法。Objective-C使用了GCD(Grand Central Dispatch)的dispatch_once函数来确保线程安全地创建单例对象,而Swift则通过静态变量和私有构造函数实现单例。这两种方式都能有效地避免多次实例化同一对象。
1万+

被折叠的 条评论
为什么被折叠?



