我正在尝试创建一个单例类。在搜索相关文档时,我发现了一个Apple Document这给出了单例的严格实现。我在哪里找到了以下代码:
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager == nil) {
sharedGizmoManager = [[super allocWithZone:NULL] init];
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedManager] retain];
}
谁能告诉我,为什么需要调用+allocWithZone:
?为什么调用 +alloc
最终会崩溃?
此外,我们还重写了+allocWithZone:
。为什么这样?为什么我们不能重写 +alloc
呢?
提前致谢。
最佳答案
您引用的文档相当旧。打开它时您可能会注意到一个警告:
Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
恕我直言,这种单例的实现是当今最好的选择:https://github.com/NYTimes/objective-c-style-guide#singletons
关于objective-c - Objective-C 中单例类的严格实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20799566/