gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:05:53 27 4
gpt4 key购买 nike

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

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com