AnalysisCocoa single-StateSingleton DesignModeThis is the content to be introduced in this article. Let's just look at the content first. If you want to write a class and want to ensure that only one instance exists, you can also get the endpoint for providing services for this specific instance, you can useSingle StateDesignMode.Single ModeIt is often used in Java and C ++.Cocoa.
Designed by yourselfSingle ModeThere are some risks, mainly considering the problems that may occur in the case of multithreading, Apple officially recommends using the following methods to achieveSingle Mode:
- static MyGizmoClass *sharedGizmoManager = nil;
-
- (MyGizmoClass*)sharedManager
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- [[self alloc] init]; // assignment not done here
- }
- }
- return sharedGizmoManager;
- }
-
- (id)allocWithZone:(NSZone *)zone
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- sharedGizmoManager = [super allocWithZone:zone];
- return sharedGizmoManager; // assignment and return on first allocation
- }
- }
- return nil; //on subsequent allocation attempts return nil
- }
- (id)copyWithZone:(NSZone *)zone
- {
- return self;
- }
-
- (id)retain
- {
- return self;
- }
-
- (unsigned)retainCount
- {
- return UINT_MAX; //denotes an object that cannot be released
- }
-
- (void)release
- {
- //do nothing
- }
-
- (id)autorelease
- {
- return self;
Summary: AnalysisCocoa single-StateSingleton DesignModeI hope this article will help you!