Singleton mode, Mode

Source: Internet
Author: User

Singleton mode, Mode

In the lifecycle of an iOS application, sometimes we only need an instance of a class. For example, when a program starts, the application state is maintained by an instance of the UIApplication class. This instance represents the entire application object and can only be one instance, the role is to achieve the access and status of some shared resources in the application.

 

The following is an example of a singleton class.

# Import "DDZPerson. h "@ interface DDZPerson () <NSCopying> @ end @ implementation DDZPersonstatic DDZPerson * _ person; // implements the singleton mode. First rewrite allocWithZone + (instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// only once _ person = [super allocWithZone: zone];}); return _ person;} // For the convenience of direct calls + (instancetype) sharedPerson {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ person = [[self alloc] init] ;}); return _ person ;}// implement the copyable method-(id) copyWithZone :( NSZone *) zone {return _ person;} @ end

 

Because basically all the class Singleton modes are similar

So they can be defined in a macro file.

 

# Define DDZSingletonH + (instancetype) sharedInstance; # define DDZSingletonM \ static id * _ instance; \ + (instancetype) allocWithZone :( struct _ NSZone *) zone {\ static deleoncetoken; \ dispatch_once (& onceToken, ^ {\_ instance = [super allocWithZone: zone] ;\\}) ;\\ return _ instance ;\}\+ (instancetype) sharedInstance {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instance = [[self alloc] init] ;\\}); \ return _ instance; \} \-(id) copyWithZone :( NSZone *) zone {\ return _ instance ;\}View Code

 

The reason why I typed \ later is that the macro definition only recognizes the last row.

The recognition will continue only after the \ is knocked

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.