Perfect single macro definition (compatible with ARC and MRC), which can be used directly in the project

Source: Internet
Author: User

Single-Case mode:
1. Always allocate only one piece of memory to create objects
2. Provide a class method that returns an internally unique object (one instance)
3. It is best to ensure that the Init method is initialized only once

The general wording of the arc under the single example (\ In the code is the definition of the macro):

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;}+ (ID) Copywithzone: (struct_nszone *) zone{return_instance;}

MRC notation:

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;}

The use of macros in a singleton class (. h file):

The use of macros in a singleton class (. m file):

Obviously, the simplification of the single case is greatly improved, which improves the reuse value of the code.

Specific Use effect:

Address of the object to print:

In the work of a single case, every rewrite annoying. Understand the role and wording of the single case, you may try this macro definition, can also propose to modify the common progress

GitHub's

Perfect single macro definition (compatible with ARC and MRC), which can be used directly in the project

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.