Safe way to create singleton with init method in Objective-C

前端 未结 3 910

I would like to take the GCD approach of using shared instances to the next step so I created the following code:

@implementation MyClass

static id sharedIn         


        
3条回答
  •  广开言路
    2021-01-11 17:49

    Instead of transparently redirecting calls to init to the singleton implementation which can cause very confusing behaviour for the users of your SDK, I suggest not allowing to call init at all:

    + (instancetype)sharedInstance {
        static dispatch_once_t once;
        dispatch_once(&once, ^{
            sharedInstance = [[self alloc] initPrivate];
        });
        return sharedInstance;
    }
    
    - (instancetype)init {
        @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"..." userInfo:nil];
    }
    
    - (instancetype)initPrivate {
        if (self = [super init]) {
            ...
        }
        return self;
    }
    

提交回复
热议问题