Singleton mode-implemented with GCD and implemented with mode-GCD

Source: Internet
Author: User

Singleton mode-implemented with GCD and implemented with mode-GCD

To use GCD to implement the singleton mode:

Step 1. Create the header file XZSingleton. h with the following code:

//. H file # define XZSingletonH (name) + (instancetype) shared # name ;//. m file # if _ has_feature (objc_arc) # define XZSingletonM (name) \ static id _ instace; \\+ (id) allocWithZone :( struct _ NSZone *) zone \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instace = [super allocWithZone: zone] ;\}); \ return _ instace; \}\+ (instancetype) shared # name \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [self alloc] init]; \}); \ return _ instace ;\}\\-(id) copyWithZone :( NSZone *) zone \{\ return _ instace ;\}# else # define XZSingletonM (name) \ static id _ instace ;\\+ (id) allocWithZone :( struct _ NSZone *) zone \{\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [super allocWithZone: zone] ;\}); \ return _ instace ;\}\+ (instancetype) shared # name \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instace = [[self alloc] init] ;\}); \ return _ instace; \}\- (id) copyWithZone :( NSZone *) zone \{\ return _ instace ;\}\\-(oneway void) release {}\-(id) retain {return self ;}\-(NSUInteger) retainCount {return 1 ;}\-(id) autorelease {return self ;}# endif

 

Step 2. The Singleton class to be implemented, such as XZDataTool ool and XZDataTool. h XZDataTool ool. m Code are as follows:

#import <Foundation/Foundation.h>@interface XZDataTool : NSObjectXZSingletonH(DataTool)@end
#import "XZDataTool.h"@implementation XZDataToolXZSingletonM(DataTool)@end

 

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.