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

前端 未结 3 901

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:46

    I would like to suggest new ways of solving your problem.

    You can use NS_UNAVAILABLE in the header file just like this:

    //Header file
    @interface MyClass : NSObject
    + (instancetype)sharedInstance
    - (instancetype)init NS_UNAVAILABLE;
    //...
    @end
    

    In this case init function will not be available from outside, will not be suggested for autocompletion, and you'll be able to normally use the init method inside implementation file.

    As you are making a singleton class I would suggest you to make new method unavailable too by adding this line to the header file:

    + (instancetype)new NS_UNAVAILABLE;
    

    There is also an old way of making methods unavailable (which can be used in header too):

    - (instancetype) init __attribute__((unavailable("Use 'sharedInstance' instead of 'init' as this class is singleton.")));
    

    This can be used if you want to prompt some message about unavailability.

提交回复
热议问题