我通常会在 viewDidLoad
中将委托(delegate)设置为 self
,但因为单例类不是 UIViewController
的子类,所以我想知道在何处为任何特定协议(protocol)设置委托(delegate)。
这是我试过但没有用的方法:
+ (instancetype)sharedInstance {
static id sharedInstance;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[[self class] alloc] init];
});
static dispatch_once_t once2;
dispatch_once(&once2, ^{
SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;
});
return sharedInstance;
}
由于上面的方法不起作用,唯一接近的是为每个类方法设置委托(delegate),如下所示:
+ (void)classMethod1 {
SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;
//class method 1 code here
}
+ (void)classMethod2 {
SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;
//class method 2 code here, etc...
}
但这看起来很愚蠢。
我想我可以在第一次使用委托(delegate)时在类之外设置委托(delegate),但随后我依赖于记住这样做,甚至知道第一次是什么时候。
最佳答案
您可以使用初始化方法来设置委托(delegate)。
例子:
static Singleton *sharedInstance = nil;
+ (Singleton *)sharedInstance {
static dispatch_once_t pred; // Lock
dispatch_once(&pred, ^{ // This code is called at most once per app
sharedInstance = [[Singleton alloc] init];
});
return sharedInstance;
}
- (id) init {
self = [super init];
if (self) {
self.delegate = self;
//more inits
//...
}
return self;
}
关于ios - 如何在非 UIVIewController 单例中设置委托(delegate)? (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26583668/