objective-c - Objective-C 中单例类的严格实现

标签 objective-c cocoa singleton

我正在尝试创建一个单例类。在搜索相关文档时,我发现了一个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/

相关文章:

c# - 在 Singleton.Instance 后面调用异步方法

objective-c - NSArrayController 在多个 NIB 中访问单例 NSMutableArray

ios - didUpdateToLocation 未在应用程序中调用

ios - 自定义 CIKernel 位移图

cocoa - Xcode 3.2 中缺少 "find options"

objective-c - NSString : how to use substring in a loop?

java - @transactional 服务在 Spring 中应该是单例还是原型(prototype)?

ios - 如何改变CALayer动画的方向

objective-c - 覆盖 UILabel 的 setText 方法?

objective-c - 使用 AVAudioPlayer 发生内存泄漏