iphone - Cocoa - 单例对象 : Where to initialize member variables?

标签 iphone cocoa singleton initialization

我想知道初始化单例类成员的最佳位置在哪里。

我正在使用 Apple 基本指南单例实现。您能指出 init 发生在哪一行吗?代码如下:

static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            sharedGizmoManager = [super allocWithZone:zone];
            return sharedGizmoManager;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)retainCount
{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

最佳答案

就像通常的类一样 - 将其添加到 block 上方:

-(id)init {
  if (self = [super init]) {
     // do init here
  }

  return self;
}

第一次访问单例时会调用它。

关于iphone - Cocoa - 单例对象 : Where to initialize member variables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1314681/

相关文章:

java - 如何创建单例类

objective-c - IBAction 中属性(property)失去值(value)

iphone - 有人使用 Sencha Touch 进​​行移动开发吗?

ios - swift 2.3 和 Xcode8.1 中的通用加密

iphone - 如何解析数组?

cocoa - 检测可移动存储何时卸载

swift - 如何使用包标识符将系统首选项启动到特定首选项 Pane ?

java - 分布式环境中的ExecutorCompletionService.take()方法

c++ - 单例翻译单元混淆

iphone - UIWebView 上的透明 UIToolBar