我通常会在self
中将委托设置为viewDidLoad
,但因为单例类不是UIViewController
的子类,所以我想知道在哪里设置任何特定的委托协议
以下是我尝试过的不起作用的内容:
+ (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;
}
由于上述方法不起作用,唯一接近的是为每个类方法设置委托,如下所示:
+ (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...
}
但这看起来很傻。
我想我可以在第一次使用它时将代理设置在类之外,但是我依赖于记住这样做,甚至知道第一次是什么时候。
答案 0 :(得分:1)
您可以使用init-method设置委托。
示例:
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;
}