iOS single-instance mode detailed

Source: Internet
Author: User

http://blog.csdn.net/a451493485/article/details/8624990

C code
  1. @implementation Appsharedatamanager
  2. Static Appsharedatamanager * Sharedatamanager = nil;
  3. @synthesize Thecurrentlanguage;
  4. @synthesize Presentmodalflag;
  5. ..........
  6. + (Appsharedatamanager *) Sharedmanager
  7. {
  8. if (Sharedatamanager = = nil)
  9. {
  10. Sharedatamanager = [[Appsharedatamanager alloc] init];
  11. }
  12. return Sharedatamanager;
  13. }
  14. -(ID) init{
  15. self = [super init];
  16. if (self) {
  17. //Object instance initialization
  18. Thecurrentlanguage = [Zonuserdefaultmanager getappdefaultlanguage];
  19. ........
  20. }
  21. return self;
  22. }

Debug discovery

Appsharedatamanager *a = [[Appsharedatamanager alloc] init];

NSLog (@ "a:%@", A);

Appsharedatamanager *b = [Appsharedatamanager Sharedmanager];

NSLog (@ "b:%@", B);

Print Out is the

2013-02-28 23:27:25.368 Zon2012[10647:c07] a:<appsharedatamanager:0x12638630>

2013-02-28 23:27:25.369 Zon2012[10647:c07] b:<appsharedatamanager:0xb584b40>

Not a memory address, which is not the same entity!

This is one of Apple's official single-case recommendations:

https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/cocoafundamentals/cocoaobjects/ Cocoaobjects.html#//apple_ref/doc/uid/tp40002974-ch4-sw32

Roughly as follows:

Java code
  1. /* Singleton.h */
  2. #Import &lt;  Foundation/foundation.h&gt;
  3. @interface Singleton:nsobject
  4. + (Singleton *) instance;
  5. @end
  6. /* SINGLETON.M */
  7. #Import "Singleton.h"
  8. static Singleton *instance = nil;
  9. @implementation Singleton
  10. + (Singleton *) Instance {
  11. if (!instance) {
  12. instance = [[super Allocwithzone:null] init];
  13. }
  14. return instance;
  15. }
  16. + (ID) Allocwithzone: (Nszone *) Zone {
  17. return [self instance];
  18. }
  19. -(ID) Copywithzone: (Nszone *) Zone {
  20. return self;
  21. }
  22. -(ID) init {
  23. if (instance) {
  24. return instance;
  25. }
  26. self = [super init];
  27. return self;
  28. }
  29. -(ID) retain {
  30. return self;
  31. }
  32. -(oneway void) Release {
  33. // do nothing
  34. }
  35. -(ID) autorelease {
  36. return self;
  37. }
  38. -(Nsuinteger) Retaincount {
  39. return Nsuintegermax;
  40. }
  41. @end

This is a very standard singleton implementation, good. However, this implementation is not thread-safe. So the great gods of each way show their divinity, and give the realization of a variety of single-case patterns.

Now put him under the step:

Java code
  1. Static MyClass *class = nil;
  2. @implementation MyClass
  3. + (MyClass *) sharedmyclass{
  4. @synchronized (self) { //To ensure the uniqueness of the entity in the case of multithreading
  5. if (! Class) {
  6. [[Self alloc] init]; //This method calls Allocwithzone
  7. }
  8. }
  9. return class;
  10. }
  11. + (ID) Allocwithzone: (Nszone *) zone{
  12. @synchronized (self) {//////To ensure the uniqueness of the entity in the case of multithreading
  13. if (! Class) {
  14. class = [Super Allocwithzone:zone]; //Make sure to use the same memory address
  15. return class;
  16. }
  17. }
  18. return nil;
  19. }
  20. -(ID) init
  21. {
  22. if (Class) {
  23. return class;
  24. }
  25. if (self = [Super init]) {
  26. //Perform some initialization
  27. }
  28. return self;
  29. }
  30. -(ID) Copywithzone: (Nszone *) zone; {
  31. return self; //Ensure that the Copy object is also unique
  32. }
  33. -(ID) retain{
  34. return self; //Ensure that the count is unique
  35. }
  36. -(unsigned) retaincount
  37. {
  38. return Uint_max; //loaded, so that the printed count is always-1
  39. }
  40. -(ID) autorelease
  41. {
  42. return self; //Ensure that the count is unique
  43. }
  44. -(oneway void) Release
  45. {
  46. //Override Count Release method do nothing
  47. }
  48. @end

Re-commissioning

MyClass *a = [[MyClass alloc] init];

NSLog (@ "a:%@", A);

MyClass *b = [MyClass sharedmyclass];

NSLog (@ "b:%@", B);

MyClass *c = [A copy];

NSLog (@ "c:%@", C);

Print Out is the

A:<myclass:0x6a1e130>

B:<myclass:0x6a1e130>

C:<myclass:0x6a1e130>

All pointing to the same block memory address

-----------------------------------cut cake Split line--------------------------------------------------------

However, this person (http://eschatologist.net/blog/?p=178) feels the tedious, so gives the following realization:

Java code
  1. @interface Somemanager:nsobject
  2. + (ID) Sharedmanager;
  3. @end
  4. /* Non-thread safe implementation */
  5. @implementation Somemanager
  6. + (ID) Sharedmanager {
  7. static id Sharedmanager = NIL;
  8. if (Sharedmanager = = nil) {
  9. Sharedmanager = [[Self alloc] init];
  10. }
  11. return Sharedmanager;
  12. }
  13. @end
  14. /* Thread-safe Implementation */
  15. @implementation Somemanager
  16. Static id Sharedmanager = NIL;
  17. + (void) Initialize {
  18. if (self = = [Somemanager class]) {
  19. Sharedmanager = [[Self alloc] init];
  20. }
  21. }
  22. + (ID) Sharedmanager {
  23. return Sharedmanager;
  24. }
  25. @end

-----------------------------------cut cake split line--------------------------------------------------------

since Apple introduced Grand Central Dispatch (GCD) (Mac OS 10.6 and iOS4.0), the use of GCD (Grand Central Dispatch) and arc (Automatic Reference counting) to implement a single case.

Java code
    1. + (schoolmanager *) sharedinstance  
    2. {  
    3.     __strong static schoolmanager *sharedmanager;   
    4.       
    5.     STATIC&NBSP;DISPATCH_ONCE_T&NBSP;ONCETOKEN;&NBSP;&NBSP;
    6.      Dispatch_once (&oncetoken, ^{  
    7.          sharedmanager = [[schoolmanager alloc] init];  
    8.      });   
    9.       
    10.      RETURN&NBSP;SHAREDMANAGER;&NBSP;&NBSP;
    11. }  

function void Dispatch_once (dispatch_once_t *predicate, dispatch_block_t block), where the first parameter predicate, This parameter is a predicate that checks whether the block of code represented by the second argument is called, and the second parameter is a block of code that will only be called once throughout the application. The code blocks in the Dispach_once function are only executed once and are thread-safe.

See the following article, with a macro implementation (HTTPS://GIST.GITHUB.COM/LUKEREDPATH/1057420):

Exampleclass.m

@implementation mysharedthing + (ID) sharedinstance{define_shared_instance_using_block (^{return [[Self alloc] init];}); @end

GCDSingleton.h

#define Define_shared_instance_using_block (BLOCK) \static dispatch_once_t pred = 0; \__strong static id _sharedobject = NIL; \dispatch_once (&pred, ^{\_sharedobject = block (); \}); \return _sharedobject; \

iOS single-instance mode detailed

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.