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

前端 未结 3 1013

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

    The general opinion is that trying to protect your singleton against that kind of bug is pointless. Whoever calls [[LUIMain alloc] init] and creates a singleton gets what they deserved.

    And the code that you wrote isn't thread safe anyway. If I call [[LUIMain alloc] init] while someone else calls sharedInstance, sharedInstance will return a different object than on the next call. (@synchronized (self) in the init method is pointless, because a second caller will have a different self).

提交回复
热议问题