OC design mode--Singleton mode

Source: Internet
Author: User

The role of the singleton pattern: it can be guaranteed that there is only one instance of a class in a program, and that this instance is easy for the outside world to access. Always allocate memory only once to this class. Since the call to the Alloc method is called allocwithzonedispatch_once This method is guaranteed to be called only once and is automatically locked and thread safe.
Modification of works to non-arc in versions prior to 6.0

Xcode6.3 under Settings, modify the project under non-arc :

Define macros to implement the generality of the Singleton. You cannot use annotations when stitching macros. The last side cannot be added /.

//# #: Two # Number of connection strings and parameters#defineSingleton_h (name) + (instancetype) shared# #name;#defineSingleton_m (name)Static ID_instance;+ (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];     }); return_instance;} +(instancetype) shared# #name {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Self alloc] init];     }); return_instance;} -(OneWayvoid) Release {}- (ID) Autorelease {return_instance;} - (ID) Retain {return_instance;} -(Nsuinteger) retaincount {return 1; } + (ID) Copywithzone: (struct_nszone *) Zone {return_instance;}

Invocation Examples:

-(ID) init

{

if (self = [super init]) {

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

Load Resources

});

}

return self;

}

Singleton_m (NetTool)

Override the init method. The macro that invokes the singleton.

How do I implement a single macro that is compatible with arc and non-arc? (add conditional compilation to judge)

OC design mode--Singleton mode

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.