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

问题描述:

我通常会在viewDidLoad中设置一个委托给self,但由于单例类不是UIViewController的子类,所以我想知道在哪里设置任何特定协议的委托。如何在非UIVIewController单例中设置委托? (iOS)

这里的东西,我试过,没有工作:

+ (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; 
} 
+0

事实上,添加一个init实例方法确实工作!我本来是有理由反对它的,因为它是以静态的方式被调用的。我不确定它为什么有效,但它确实有效。 – kraftydevil 2014-10-27 16:56:20

+0

是的,这是令人困惑的,但虽然该方法是静态的,它会创建一个对象。这也意味着你可以添加非静态方法并调用它们,例如 - (void)logMe {NSLog(@“logMe”); }并用[[Singleton sharedInstance] logMe]调用它; – Thorsten 2014-10-27 17:05:37