Re: Getting class when instantiating a singleton


Alex Zavatone
 


On Aug 30, 2017, at 3:54 PM, Ben Kennedy <ben@...> wrote:


On 30 Aug 2017, at 1:37 pm, Alex Zavatone <zav@...> wrote:

In iOS, when I’m making an Objective-C singleton, in the public method that returns the instanceType, we need to put the class name.  Is there a way to do this dynamically instead of entering the class name all the time?  

Why is this necessary? Apologies if I'm missing something obvious, but what's wrong with literally using DataSingleton (in your example)?

Even if the method is called on a subclass it should still work as desired because you're calling [self alloc], not [DataSingleton alloc].

-ben




I’m able to turn the sharedInstance method from being dependent on my changing the class name and being this:

@implementation CrewActionsDataSingleton

+ (instancetype)sharedInstance
{
    static TheClassName *instance;
    static dispatch_once_t onceToken;

    

    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

 To this:

@implementation CrewActionsDataSingleton

+ (instancetype)sharedInstance
{
    static id instance; 
    static dispatch_once_t onceToken;

    

    dispatch_once(&onceToken, ^{
        [self new];
    });
    return instance;
}

I’m able to turn the sharedInstance method from being dependent on my changing the class name and being this: Good point on making a snippet.  I think I change computers too often though. It’s another thing to manage.

Thanks for the tips.  Best brain trust ever.

Alex Zavatone

Join cocoa@apple-dev.groups.io to automatically receive all group messages.