2014-10-27 65 views
0

我通常會在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... 
} 

但是,這看起來很愚蠢。

我想我可以在第一次使用它時在類之外設置委託,但那時我要記住這麼做,甚至不知道第一次是什麼時候。

回答

1

您可以使用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