Cocoa - Singleton对象:在哪里初始化成员变量?

Yoh*_* T. 8 iphone cocoa singleton initialization

我想知道初始化单身人士课程成员的最佳位置在哪里.

我正在使用Apple基本指南单例实现.你能指出一下这些线路是怎么发生的吗?代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

Rud*_*udi 18

它与通常的类一样 - 在块上方添加:

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

  return self;
}
Run Code Online (Sandbox Code Playgroud)

首次访问单例时将调用它.