kraftydevil
kraftydevil

Reputation: 5246

How to set delegate in non-UIVIewController singleton? (iOS)

I would typically set a delegate to self in viewDidLoad, but because the singleton class is not a subclass of UIViewController, I'm wondering where to set the delegate for any particular protocol.

Here is something that I've tried that didn't work:

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

Since the above doesn't work, the only thing that comes close is to set the delegate for every class method like this:

+ (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...
}

But this just seems silly.

I suppose I could set the delegate outside of the class the first time it gets used, but then I'm depending on remembering to do that or even knowing when that first time is.

Upvotes: 0

Views: 467

Answers (1)

Thorsten
Thorsten

Reputation: 3122

You can use the init-method to set the delegate.

Example:

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

Upvotes: 1

Related Questions