如何在非UIVIewController单例中设置委托?(iOS)

如何在非UIVIewController单例中设置委托?(iOS),ios,delegates,singleton,Ios,Delegates,Singleton,我通常会在viewdiload中将委托设置为self,但由于singleton类不是UIViewController的子类,我想知道在哪里为任何特定协议设置委托 以下是我尝试过的一些不起作用的东西: + (instancetype)sharedInstance { static id sharedInstance; static dispatch_once_t once; dispatch_once(&once, ^{ sharedInstan

我通常会在
viewdiload
中将委托设置为
self
,但由于singleton类不是
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...
}
但这似乎很愚蠢


我想我可以在第一次使用委托时将其设置在类之外,但这取决于我是否记得这样做,甚至是否知道第一次使用委托的时间。

您可以使用init方法设置委托

例如:

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;
}

事实上,添加init实例方法确实有效!我最初反对它,因为它是以静态方式调用的。我不确定为什么它是有效的,但它确实起作用。是的,这令人困惑,但尽管该方法是静态的,但它创建了一个对象。这也意味着您可以添加非静态方法并调用它们,即-(void)logMe{NSLog(@“logMe”);}并使用[[Singleton sharedInstance]logMe]调用它;