Singleton design mode for IOS development and IOS development

Source: Internet
Author: User

Singleton design mode for IOS development and IOS development

This article will explain the singleton design mode in IOS development from four aspects:

I. What is the singleton Design Pattern II. Why should we use Singleton Design Pattern III. Basic usage of Singleton Design Pattern IV. encapsulation of custom Singleton design pattern code

 

I. What is a singleton design model?

A single instance is a single instantiated object, ensuring that one class has only one instance. Generally, when we instantiate a class (such as alloc and new),It is not guaranteed that the object instantiated each time is a unique instance. To ensure that the memory address remains unchanged during multiple instantiation of this class, we need to introduce the singleton design mode.

 

 

Ii. Why should we use the singleton design model?

1. Singleton will prevent other objects from instantiating copies of their own Singleton objects, so that all objects can access a unique instance, such as multiple music players on the mobile phone, however, you need to play the final music in the player for the user. To improve the user experience, this type of playing tool class needs to be implemented using a singleton.

2. thread security can be improved. We use the dispatch_once function when instantiating a single instance.

void dispatch_once(    dispatch_once_t *predicate,    dispatch_block_t block);

During the entire program declaration cycle, this function only executes a block object once, and the system has locked us. Therefore, when multiple threads snatch the same resource, he is also safe

 

 

III. Basic usage of Singleton Design Mode

Generally, the singleton design mode only needs to override two methods. Of course, it is necessary to instantiate the share or standard class methods of the object.

+ (Id) allocWithZone :( NSZone *) zone; // NSCopying is not required to overwrite the copyWithZone method after IOS9.0.-(id) copyWithZone :( NSZone *) zone;

 

Class methods for implementing singleton:

Static id _ instance; + (instancetype) implements audioplayer {/** it is safe to execute dispatch_once at a time. The system has locked us, so when multiple threads snatch the same resource, it is also safe */static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {NSLog (@ "--- once ---"); _ instance = [[self alloc] init];}); return _ instance ;}

 

Override of the above two methods

+ (instancetype)allocWithZone:(struct _NSZone *)zone {        static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance = [super allocWithZone:zone];    });    return _instance;    }- (id)copyWithZone:(NSZone *)zone {    return _instance;}

 

The Singleton design mode has some differences between the internal mechanism of ARC and non-ARC. The following describes the singleton design modes for the two memory management modes respectively.

In ARC, the above Code is sufficient to implement the singleton design pattern, and the following code does not need to be rewritten.

 

If MRC is used, the following four methods must be rewritten based on the preceding two methods:

- (id)retain;- (NSUInteger)retainCount;- (void)release;- (id)autorelease;
// In MRC, rewrite the following method-(oneway void) release {}-(instancetype) retain {return _ instance;}-(instancetype) autorelease {return _ instance ;} -(NSUInteger) retainCount {return 1 ;}

 

The above is the usage of the singleton design mode in ARC or MRC. If you need to be compatible with MRC or ARC at the same time, you need to judge the abbreviation code. We generally use Conditional compilation for judgment:

# If _ has_feature (objc_arc) // ARC NSLog (@ "insert the ARC Code in MRC is also possible, And no error is reported in MRC, but not executed "); # else // MRC NSLog (@ "it is also possible to insert MRC code under ARC, and no error is reported under ARC, but not executed"); # endif

 

Iv. Code encapsulation of custom Singleton Design Mode

During our work, if we need to customize the singleton design mode, the above Code will inevitably be written repeatedly. To improve work efficiency, we can consider encapsulating the code.

Singleton_h (DBTool) singleton_m. the content in the H file is. the merging parameters in the content macro in the m file are two ##*///. h file extraction # define singleton_h (name) \ + (instancetype) share # name; # if _ has_feature (objc_arc) // In the ARC environment # define singleton_m (name) \ static id _ instance; \\+ (instancetype) share ## name {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instance = [[self alloc] init] ;\}); \ return _ instance ;\}\\ + (instancetype) allocWithZone :( struct _ NSZone *) zone {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\_ instance = [super allocWithZone: zone] ;\}); \ return _ instance; \}\- (id) copyWithZone :( NSZone *) zone {\ return _ instance; \}# else // non-ARC environment (MRC) # define singleton_m (name) \ static id _ instance; \\+ (instancetype) share ## name {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instance = [[self alloc] init] ;\}); \ return _ instance ;\}\\ + (instancetype) allocWithZone :( struct _ NSZone *) zone {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\_ instance = [super allocWithZone: zone] ;\}); \ return _ instance; \}\- (id) copyWithZone :( NSZone *) zone {\ return _ instance ;\}\\-(oneway void) release {}\-(instancetype) retain {return _ instance ;}\-(instancetype) autorelease {return _ instance ;}\-(NSUInteger) retainCount {return 1 ;}# endif

 

 

If there are any mistakes in this article, please correct them and make progress together. Thank you!

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.