iOS OC Single macro definition

Source: Internet
Author: User

#undef As_singleton

#define As_singleton (__class) \

-(__class *) sharedinstance; \

+ (__class *) sharedinstance;

#undef Def_singleton

#define Def_singleton (__class) \

-(__class *) sharedinstance \

{ \

return [__class sharedinstance]; \

} \

+ (__class *) sharedinstance \

{ \

Static dispatch_once_t once; \

Static __class * __SINGLETON__; \

Dispatch_once (&once, ^{__singleton__ = [[[Self class] alloc] init];}); \

return __singleton__; \

} \

+ (Instancetype) Allocwithzone: (struct _nszone *) zone \

{ \

Static dispatch_once_t once; \

Static __class * __SINGLETON__; \

Dispatch_once (&once, ^{__singleton__ = [Super Allocwithzone:zone];}); \

return __singleton__; \

}

How to use: Declare As_singleton (__class) in. h

. M declaration Def_singleton (__class)

Explanation: In order to prevent others from accidentally using the Alloc/init way to create the example, but also to prevent others deliberately, we have to ensure that no matter how the creation can only be the same instance object, this will have to rewrite Allocwithzone; I didn't have this before, this is Alloc init. and shareinstance created not the same

Reference Link: Http://www.cocoachina.com/ios/20160713/17017.html?ref=myread This is written in detail.

iOS OC Single macro definition

Related Article

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.