一个第三方库使用我的类初始化:
ClassA *a = [[MyClass alloc] init]];
我需要MyClass
作为共享实例(也称为singleton),但我无法修改执行MyClass
初始化的第三方方式
我试图覆盖init
方法如下:
- (instancetype)init
{
return [[self class] sharedInstance];
}
+ (LoopMeNativeEvent *)sharedInstance
{
static LoopMeNativeEvent *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [LoopMeNativeEvent new];
});
return _sharedInstance;
}
但遗憾的是,new
导致alloc init
被执行。
我知道最简单的方法是有两个单独的类:
MyClass
将通过alloc init
MySharedClass
单身是否有可能只用一个班级来实现这个目标?
答案 0 :(得分:0)
继承怎么样,
创建一个名为ChildClass的新类,它继承自MyClass并添加以下两个方法
+ (instancetype)sharedInstance
{
static ChildClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[ChildClass alloc] init];
});
return sharedInstance;
}
- (id)init
{
self = [super init];
return self;
}
答案 1 :(得分:0)
试试这个。它肯定会解决你的问题。
- (instancetype)init
{
return [[self class] sharedInstance];
}
+ (LoopMeNativeEvent *)sharedInstance {
// structure used to test whether the block has completed or not
static dispatch_once_t onceToken = 0;
// initialize sharedObject as nil (first call only)
static LoopMeNativeEvent *_sharedInstance = nil;
// executes a block object once and only once for the lifetime of an application
dispatch_once(&onceToken, ^{
_sharedInstance = [[LoopMeNativeEvent alloc] init];
});
// returns the same object each time
return _sharedInstance;
}