The single-instance design pattern for iOS development

Source: Internet
Author: User

This article will explain the Singleton design pattern in iOS development from four aspects:

first, what is a single-case design mode Two, why should we use a single case design pattern three, the basic usage of the single-case design pattern four, custom single-instance design pattern code Encapsulation

first, what is a singleton design mode

The so-called Singleton, which is a single instantiated object, guarantees that a class has and only one instance. Typically, when we instantiate a class (for example, alloc, new, etc.), there is no guarantee that the object that is instantiated is a unique instance each time. It is necessary to introduce a singleton design pattern in order to ensure that the memory address of the class can be guaranteed to be constant during multiple instantiation.

Second, why should we use a single case design mode

1. Singleton blocks other objects from instantiating copies of their own Singleton objects, ensuring that all objects have access to unique instances, such as multiple music players in the phone, but need to play the music from the last player that was opened for the user, to improve the user experience, This type of playback tool class needs to be implemented in a single case.

2, can improve thread safety, in the instantiation of a single case we used a dispatch_once function

void dispatch_once (    *predicate,    dispatch_block_t block);

This function in the entire program's declaration period, only one time to execute a block object, the system has helped us lock, so when multiple threads rob the same resource, he is also safe

three, the basic usage of the single case design pattern

Typically, a generic singleton design pattern requires only two methods to be rewritten, and of course the share or standard class method needed to instantiate the object is necessary.

+ (ID) Allocwithzone: (Nszone *) zone; // IOS9.0 no need to introduce nscopying to Copywithzone method rewrite will not error -(ID) Copywithzone: (Nszone *) zone;

To implement a class method for a single example:

Static ID _instance; + (instancetype) shareaudioplayer {    /* * *     one-     time execution dispatch_once is safe, the system has helped us to lock, So when multiple threads rob the same resource, he is also safe      */    static  dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        NSLog (@ "---once---" );                 = [[Self alloc] init];    });     return _instance;}

Rewrite of the above two methods

+ (Instancetype) Allocwithzone: (struct _nszone *) zone {        static  dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        = [Super Allocwithzone:zone];    });     return _instance;    } -(ID) Copywithzone: (Nszone *) zone {    return  _instance;}

There are some differences between the single-case design mode and the internal mechanism of Arc and non-arc, and the following two types of memory management modes are described in the single-case design mode.

If the above code is sufficient to implement the singleton design pattern under arc, the following code does not need to be rewritten.

If under MRC, the following four methods are rewritten based on overriding the two methods:

-(ID) retain; - (Nsuinteger) retaincount; -(void) release; -(ID) autorelease;
// The MRC also overrides the following methods void ) Release {}-(instancetype) retain {return  _instance;} -(Instancetype) autorelease {return  _instance;} -(Nsuinteger) retaincount {return1;}

The above is the use of single-instance design mode under ARC or MRC. If you need to be compatible with MRC or arc, you need to judge the abbreviation code, we generally use conditional compilation to judge:

#if // ARC         NSLog (@ "MRC Insert Arc Code is also possible, in the MRC will not error, but will not be executed "); #else  // MRC     NSLog (@ "arc Insert MRC Code is also possible, under the arc will not error, but will not be executed "); #endif

Iv. Customizing the encapsulation of a single-instance design pattern code

In the process of our work, if you need to customize the singleton design pattern, the above code will inevitably be written repeatedly, in order to improve the efficiency, you can consider the code encapsulation

Singleton_h (DBTool) singleton_m (DBTool)/** single-case extraction macro, only need to change two parts, one is the contents of the. h file, one is the contents of the. m file inside the mosaic parameter with two # # *///. h file separately extracted # Define SINGLETON_H (name) + (instancetype) share# #name; #if __has_feature (OBJC_ARC)//Arc # 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 _instan Ce     + (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 _in Stance;} -(Instancetype) autorelease {return _instance;}-(Nsuinteger) Retaincount {return 1;} #endif

If there are any errors in this article, welcome to make bricks, common progress, thank you!

The single-instance design pattern for iOS development

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.