IOS macros define a single case

Source: Internet
Author: User

Sometimes it is because of the frequent creation of a singleton object and headache, one way to write many times? Of course you can use the OC language for encapsulation. However, the following describes a package in C language. As long as the following method is implemented, a singleton object will be built after two sentences.

1. Create a new. h file and implement the following methods in the file:

1/. h2 #defineSingleton_interface (Class) + (Instancetype) shared# #class;3 4 //. M5 #defineSingleton_implementation (Class)6 Static class*_instance;7 8+ (ID) Allocwithzone: (struct_nszone *) Zone9 { Ten     Staticdispatch_once_t Oncetoken; OneDispatch_once (&oncetoken, ^{  A_instance =[Super Allocwithzone:zone]; -     });  -  the     return_instance; - }  -  -+ (Instancetype) shared##class  + {  -     if(_instance = =Nil) {  +_instance = [[classalloc] init];  A     }  at  -     return_instance; -}

2. How to use.

Write the first sentence in the. h file in the class that you want to create the singleton in:

Singleton_interface (class name)
Write the second sentence in the. m file:


Well, after importing the header file in any project, and then implementing the two sentences in the class, you can easily use the singleton, and no longer have to write a lot of code frequently. Looks like it's not very big on!

IOS macros define a single case

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.