gpt4 book ai didi

Objective-c 单例基类

转载 作者:太空狗 更新时间:2023-10-30 04:00:41 24 4
gpt4 key购买 nike

有没有一种方法可以使用 objective-c 创建单例模式,使客户端代码能够获取其任何子类的共享实例?

我试过:

@interface Base : NSObject {}
+(id)instance;
@end

@implementation Base
static id _instance;
+(id)instance {
if (!_instance) {
_instance = [[self alloc] init];
}
return _instance;
}
@end

但是调用任何子类的[AmazingThing instance] 只会返回通过该机制创建的第一个实例,无论_instance 是什么类型。有什么干净的解决方法吗?

编辑

我意识到(在回复已删除的答案时)我可以通过将实现更改为:

static NSMutableDictionary *_instances;

+(id)instance {
if (!_instances) {
_instances = [[NSMutableDictionary alloc] init];
}
id instance = [_instances objectForKey:self];
if (!instance) {
instance = [[self alloc] init];
[_instances setObject:instance forKey:self];
}
return instance;
}

它现在按预期工作。尽管如此,我还是很想知道是否有更好的方法来做到这一点。

最佳答案

我会这样做:

+(id) instance
{
static id theInstance = nil;
if (theInstance == nil)
{
theInstance = [[self alloc] init];
}
return theInstance;
}

当然,您需要在基类的每个子类中使用该方法,以便为每个类获取不同的静态变量。但是您会在基类 header 中创建一个 #define:

#define CREATE_INSTANCE           \
+(id) instance \
{ \
static id theInstance = nil; \
if (theInstance == nil) \
{ \
theInstance = [[self alloc] init]; \
} \
return theInstance; \
}

然后每个实现中都有定义:

@implementation SubClass

CREATE_INSTANCE

// other stuff

@end

关于Objective-c 单例基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383312/

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