IOS single case (Singleton) Summary and third Library Reference Singleton

Source: Internet
Author: User
Tags instance method

Reference: HTTP://BLOG.CSDN.NET/LOVEFQING/ARTICLE/DETAILS/8516536#T3

http://blog.csdn.net/kindazrael/article/details/7917863

The singleton pattern is used when a class can have only one instance, typically this "singleton " represents a physical device such as a printer, or some kind of virtual resource or system attribute, such as a program's engine or data, that can not have multiple instances at the same time. The simplest example is that when the user opens the QQ space to play music, here is a singleton, if not a single case, click on other pages QQ music will automatically start from the beginning. It is necessary to control it with a single-case pattern.

What the singleton model needs to achieve

1. encapsulating a shared resource

2. provide a fixed instance creation method

3. provide a standard instance access interface

Creating a singleton pattern

This article takes the example of creating a Mysingletonclass singleton pattern. First, we need to define a class of Mysingletonclass.

[CPP]View Plaincopy
    1. @interface Mysingletonclass:nsobject {
    2. }

and add a class method for it (note that this is not an instance method)+ (ID) sharedinstance; a basic implementation is as follows:


static Mysingletonclass *sharedinstance = nil;
    1. + (mysingletonclass *) sharedinstance{  
    2.      @synchronized (self)  {  
    3.          if (sharedinstance == nil)  {  
    4.            sharedinstance = [[Mysingletonclass alloc]init];
    5.         }  
    6.      }  
    7.     return sharedinstance;  
    8. }  

In the above code (the keyword @synchronized is used to ensure that our singleton thread-level security can be applied in multithreaded mode. Thestatic variable sharedcldelegate is used to store a pointer to a singleton, and forcing all access to the variable must pass the class method + (ID) sharedinstance, on the + ( ID) Sharedinstance the creation of the instance the first time it is called. It is worth noting that the code above is [[Self class] alloc] instead of [Mysingletonclass alloc], which generally produces the same effect.

Control of the instantiation

In order to fully realize the uniqueness of the instance, it is necessary to avoid the instance being created multiple times by certain means. + (ID) sharedinstance controls the creation and access of the singleton, but does not control the code elsewhere to create more instances through the Alloc method, so we also overload any method that involves allocation, These methods include +new, +alloc,+allocwithzone:,-copywithzone:, and-mutablecopywithzone: Plus, + (ID) sharedinstance A minor modification is also required.

  1. + (ID) hiddenalloc
  2. {
  3. return [Super alloc];
  4. }
  5. + (ID) alloc
  6. {
  7. NSLog (@'%@: Use +sharedinstance instead of +alloc ', [[Self class] name];
  8. return nil;
  9. }
  10. + (ID)new
  11. {
  12. return [self alloc];
  13. }
  14. + (ID) Allocwithzone: (nszone*) zone
  15. {
  16. return [self alloc];
  17. }
  18. -(ID) Copywithzone: (Nszone *) zone
  19. { //-copy inherited from NSObject Calls-copywithzone:
  20. NSLog (@"Mysingletonclass:attempt to-copy may be a bug.");
  21. [Self retain];
  22. return self;
  23. }
  24. -(ID) Mutablecopywithzone: (Nszone *) zone
  25. {
  26. //-mutablecopy inherited from NSObject Calls-mutablecopywithzone:
  27. return [self copywithzone:zone];
  28. }
  29. + (ID) sharedinstance modified as follows:
  30. + (Mysingletonclass *) sharedinstance {
  31. @synchronized (self) {
  32. if (sharedcldelegate = = nil) {
  33. [[Self class] hiddenalloc] init]; //Assignment not do here
  34. }
  35. }
  36. return sharedcldelegate;
  37. }

If the subclass of the class is not considered,the +hiddenalloc method can be omitted. Since we are using [Self class] to implement dynamic recognition of the type, using [[Selfclass] hiddenalloc] can avoid calling to the overloaded Alloc method. In addition,Hiddenalloc provides an opportunity to invoke the original Alloc method for possible subclasses . The overloaded Alloc method above simply gives a log message and returns nil. The copying method simply increases the count of retain and does not return a new instance. This is also a manifestation of the nature of the singleton pattern, because technically, copying a single case is wrong (because it is a "singleton ") so in the Copywithzone method we give an error message, and of course we can throw a exception.

Single-Instance Destruction

usually we call the following method in the-(void) Applicationwillterminate: (uiapplication *) Application method:

    1. + (void) Attemptdealloc
    2. {
    3. if ([sharedcldelegate retaincount]! = 1)
    4. return;
    5. [Sharedcldelegate release];
    6. MyInstance = nil;
    7. }

It is worth noting that the above Attemptdealloc method, as its name implies, is simply trying to release the Singleton. If the count of retain is not 1, there are other places where retain messages have been sent to the single case . Consider that the lifetime of a singleton pattern is the end of the entire program. Therefore, there is no need to send a retain message to this single case anywhere in the program , even if the singleton is referenced. Instead of invoking the Sharedinstance method to refer to this singleton, it is safe to do so and is consistent with the technical implications of the Singleton pattern.

Here you need to set a parameter to manage memory manually.

the singleton mode app in iOS

There are several classes in IOS that use singleton patterns, such as NSApplication, Nsfontmanager, Nsdocumentcontroller,nshelpmanager, NSNull, Nsprocessinfo, Nsscriptexecutioncontext, nsuserdefaults.

  1. Official advice
  2. Since there is a certain risk in designing a single mode, the main consideration is the problem that may occur in multi-threaded situations, so Apple recommends using the following methods to achieve a single mode:
  3. static Mygizmoclass *sharedgizmomanager = nil;
  4. + (mygizmoclass*) Sharedmanager
  5. {
  6. @synchronized (self) {
  7. if (Sharedgizmomanager = = nil) {
  8. [[Self alloc] init]; Assignment not do here
  9. }
  10. }
  11. return sharedgizmomanager;
  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. -(ID) retain
  28. {
  29. return self;
  30. }
  31. -(unsigned) retaincount
  32. {
  33. return Uint_max; Denotes an object, cannot be released
  34. }
  35. -(void) Release
  36. {
  37. Do nothing
  38. }
  39. -(ID) autorelease
  40. {
  41. return self;
  42. }
  43. Since the singleton mode basically conforms to the above design, when there are many classes to be designed into a singleton pattern, you can define
  44. A single template macro to improve the reuse of programs and reduce unnecessary errors.
  45. #define SYNTHESIZE_SINGLETON_FOR_CLASS (classname) \
  46. \
  47. static classname *shared# #classname = nil; \
  48. \
  49. + (classname *) shared# #classname \
  50. { \
  51. @synchronized (self) \
  52. { \
  53. if (shared# #classname = = nil) \
  54. { \
  55. shared# #classname = [[Self alloc] init]; \
  56. } \
  57. } \
  58. \
  59. return shared# #classname; \
  60. } \
  61. \
  62. + (ID) Allocwithzone: (nszone *) zone \
  63. { \
  64. @synchronized (self) \
  65. { \
  66. if (shared# #classname = = nil) \
  67. { \
  68. shared# #classname = [Super Allocwithzone:zone]; \
  69. return shared# #classname; \
  70. } \
  71. } \
  72. \
  73. Returnnil; \
  74. } \
  75. \
  76. -(ID) Copywithzone: (nszone *) zone \
  77. { \
  78. returnself; \
  79. } \
  80. \
  81. -(ID) retain \
  82. { \
  83. returnself; \
  84. } \
  85. \
  86. -(Nsuinteger) retaincount \
  87. { \
  88. return Nsuintegermax; \
  89. } \
  90. \
  91. -(void) release \
  92. { \
  93. } \
  94. \
  95. -(ID) autorelease \
  96. { \
  97. returnself; \
  98. }

Usage: Suppose the Apppreference class is to implement a single case

#import "AppPreference.h"

#import "SingletonTemplate.h"

@implementation Apppreference

Use the macro template to generate the code required for the singleton

Synthesize_singleton_for_class (apppreference)

This is a test method

+ (void) Test {

Use a single case

Apppreference *apppreference = [Apppreference sharedapppreference];

}

@end

IOS single case (Singleton) Summary and third Library Reference Singleton

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.