Force deletion of singleton in test code that was created with dispatch_once

后端 未结 2 1610
心在旅途
心在旅途 2021-01-23 11:31

I\'m writing some unit test code for a model class and want to simulate the behavior of the class during app exit and relaunch. I could achieve this by deleting and re-allocing

相关标签:
2条回答
  • 2021-01-23 11:40

    sure something like this would be fine for unit testing, you can turn it off for prod:

    static MyModel *singleton = nil;
    
    + (id) sharedInstance
    {   
       if(!singleton)
        {
            singleton = [self new];
        }
        return singleton;
    }
    + (void)resetSingleton
    {
        [singlelton release];
        singleton = nil;
    }
    
    0 讨论(0)
  • 2021-01-23 12:01
    static MyModel *singleton = nil;
    static dispatch_once_t onceToken;
    
    + (instancetype) sharedInstance
    {
        dispatch_once(&onceToken, ^ {
            if (singleton==nil){
                singleton = [[MyModel alloc] initSharedInstance];
            }
        });
        return singleton;
    }
    
    +(void)setSharedInstance:(MyModel *)instance {
        onceToken = 0;
        singleton = instance;
    }
    

    Nil it:

    [MyModel setSharedInstance:nil];
    

    Note that you can also set it to an arbitrary class to mock it.

    [MyModel setSharedInstance:someMock];
    
    0 讨论(0)
提交回复
热议问题