One-sentence OC Singleton mode and one-sentence OC Mode

Source: Internet
Author: User

One-sentence OC Singleton mode and one-sentence OC Mode

Create a new header file and define the following macro:

//. H file implementation # define SingletonH (methodName) + (instancetype) shared # methodName ;//. implementation of the m file # if _ has_feature (objc_arc) // It is ARC # define SingletonM (methodName) \ static id _ instace = nil; \ + (id) allocWithZone :( struct _ NSZone *) zone \ {\ if (_ instace = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [super allocWithZone: zone] ;\}) ;\}\ return _ instace ;\}\\-(id) init \{\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [super init] ;\}); \ return _ instace ;\}\+ (instancetype) shared # methodName \ {\ return [[self alloc] init] ;\}\+ (id) copyWithZone :( struct _ NSZone *) zone \{\ return _ instace; \}\+ (id) mutableCopyWithZone :( struct _ NSZone *) zone \ {\ return _ instace ;\}# else // not ARC # define SingletonM (methodName) \ static id _ instace = nil; \ + (id) allocWithZone :( struct _ NSZone *) zone \ {\ if (_ instace = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [super allocWithZone: zone] ;\}) ;\}\ return _ instace ;\}\-(id) init \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instace = [super init] ;\}); \ return _ instace; \}\+ (instancetype) shared # methodName \ {\ return [[self alloc] init] ;\}\- (oneway void) release \ {\}\\-(id) retain \ {\ return self ;\}\\-(NSUInteger) retainCount \ {\ return 1; \} \ + (id) copyWithZone :( struct _ NSZone *) zone \ {\ return _ instace ;\}\+ (id) mutableCopyWithZone :( struct _ NSZone *) zone \ {\ return _ instace ;\}# endif

Then

. H file write SingletonH (MyMethodName)

. M file write SingletonM (MyMethodName)

Done!

 

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.