Analysis of Cocoa single-State singleton Design Mode

Source: Internet
Author: User

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:

 
 
  1. static MyGizmoClass *sharedGizmoManager = nil;  
  2.    
  3.  (MyGizmoClass*)sharedManager  
  4. {  
  5.     @synchronized(self) {  
  6.         if (sharedGizmoManager == nil) {  
  7.             [[self alloc] init]; // assignment not done here  
  8.         }  
  9.     }  
  10.     return sharedGizmoManager;  
  11. }  
  12.    
  13.  (id)allocWithZone:(NSZone *)zone  
  14. {  
  15.     @synchronized(self) {  
  16.         if (sharedGizmoManager == nil) {  
  17.             sharedGizmoManager = [super allocWithZone:zone];  
  18.             return sharedGizmoManager;  // assignment and return on first allocation  
  19.         }  
  20.     }  
  21.     return nil; //on subsequent allocation attempts return nil  
  22. }  
  23.   (id)copyWithZone:(NSZone *)zone  
  24. {  
  25.     return self;  
  26. }  
  27.    
  28.  (id)retain  
  29. {  
  30.     return self;  
  31. }  
  32.    
  33.  (unsigned)retainCount  
  34. {  
  35.     return UINT_MAX;  //denotes an object that cannot be released  
  36. }  
  37.    
  38.  (void)release  
  39. {  
  40.     //do nothing  
  41. }  
  42.    
  43. (id)autorelease  
  44. {  
  45.     return self; 

Summary: AnalysisCocoa single-StateSingleton DesignModeI hope this article will help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.