Singleton in iOS Objective C doesn't prevent more than one instance

后端 未结 9 1570
长情又很酷
长情又很酷 2020-11-29 08:53

I know there are several threads on this, but none answer my questions.

I\'ve implemented my singleton class like this (being aware of the controversy about singleto

9条回答
  •  盖世英雄少女心
    2020-11-29 09:34

    You can't make the init method private, like you would do in Java with the constructor. So nothing stops you from calling [[MyClass alloc] init] which indeed creates a different object. As long as you don't do that, but stick to the sharedInstance method, your implementation is fine.

    What you could do: have the init method raise an exception (e.g. with [self doesNotRecognizeSelector:@_cmd]) and perform the initialization in a different method (e.g. privateInit) which is not exposed in the header file.

提交回复
热议问题