iOS Development-Singleton mode

Source: Internet
Author: User

  • What is a singleton mode?
    > is the 1 types of development design pattern ( total 23 kinds )
    > It can guarantee the process of running a program, a class has only one instance (an object), and the instance is easy for outside access, so as to easily control the number of instances, and save system resources
    > Use occasions:
    Share a single resource throughout the application (this resource only needs to be initialized 1 times)

  • The basic realization of Singleton mode
    1. Lazy mode
    // 1. Define a static global variable in this class to prevent access by external Extren
    Static ID _instance;

    /**

    Static: Modifier variable

    1> Modifying global variables

    * Global variables are scoped to the current file only, and other files cannot be accessed with the Extren keyword

    2> Modifying local variables:

    * The life cycle of local variables is similar to global variables

    * But cannot change scope

    * Can ensure that local variables are always initialized only 1 times, in the course of the program, always only 1 minutes of memory

    */

    /** 2. Rewrite the llocwithzone of this class: method to Make sure that you assign only one memory address to this class * The method is called internally by the Alloc method*/+ (ID) Allocwithzone: (struct_nszone *) zone{if(_instance = = nil) {//prevent frequent lock -up@synchronized (self) {//lock to avoid errors in multiple threads and create multiple objects            if(_instance = = nil) {//prevent creation of multiple_instance =[Super Allocwithzone:zone]; }        }    }    return_instance;}//3. Provide a shared method for the external invocation of the singleton (which is provided by the General Singleton) to ensure that only the init once +(instancetype) sharedmusictool{if(_instance = = nil) {//prevent frequent lock -up@synchronized (self) {if(_instance = = nil) {//prevent creation of multiple_instance =[[Self alloc] init]; }        }    }    return_instance;}//4. Override Copywithzone: method to avoid creating multiple objects when using copy- (ID) Copywithzone: (Nszone *) zone{return_instance;}

    2. A Hungry man mode (when the class is loaded into the OC Runtime (memory), it is called once to generate the singleton (a class will only be loaded once))

    //1. Define a static global variable in this class to prevent access by external ExtrenStatic ID_instance;/** 2. Rewrite the llocwithzone of this class: method, there is no lock, because the program has just started, the thread is not loaded, there is no thread unsafe problem*/+ (ID) Allocwithzone: (struct_nszone *) zone{            if(_instance = = nil) {//prevent creation of multiple_instance =[Super Allocwithzone:zone]; }    return_instance;}//3. Provide a shared method to allow the outside world to invoke this singleton (the General Singleton will provide this method)+(instancetype) sharedmusictool{return_instance;}//4. Override Copywithzone: method to avoid creating multiple objects when using copy- (ID) Copywithzone: (Nszone *) zone{return_instance;}//5. Rewrite the load class method and alloc it inside//This method is called once when the program starts and loads the class.+ (void) load{_instance=[[Self alloc] init]; }

  • implementing a singleton pattern with GCD
    //1.Static ID_instance;/** 2. Rewrite with GCD's Dispatch_once method*/+ (ID) Allocwithzone: (struct_nszone *) zone{Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];   }); return_instance;}//3.+(instancetype) sharedmusictool{Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Self alloc] init];    }); return_instance;}//4.- (ID) Copywithzone: (Nszone *) zone{return_instance;}

  • Singleton mode under non-Arc
    // as in front of the ACR, then override the following methods
    No release.
    void ) Release {}//  retain after a copy -(ID) retain {    return  Self;} // The counter is always 1- (Nsuinteger) retaincount    {return1;} // prevent being put into automatic count pool release -(ID) autorelease {    return self ;}

  • implementing a single example with a macro definition (suitable for arc and MRC)
    // create a new. h file or PCH file and copy the code in. Import in the class that needs to implement the singleton and use the macro (the corresponding class name is passed in parentheses) to
    //macro definitions used in. h Files#defineHjsingletonh (name) + (instancetype) shared# #name;#if__has_feature (OBJC_ARC)//the current compiler environment is arc//macro definitions used in. m Files#defineHJSINGLETONM (name)Static ID_instace;+ (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];}); return_instace;} +(instancetype) shared# #name {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[[Self alloc] init];}); return_instace;} - (ID) Copywithzone: (Nszone *) Zone {return_instace;}#else//the current compiler environment is MRC//macro definitions used in. m Files#defineHJSINGLETONM (name)Static ID_instace; + (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];     }); return_instace;} +(instancetype) shared# #name {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[[Self alloc] init];     }); return_instace;} - (ID) Copywithzone: (Nszone *) Zone {return_instace;} -(OneWayvoid) Release {}- (ID) Retain {returnSelf ;} -(Nsuinteger) Retaincount {return 1;} - (ID) Autorelease {returnSelf ;}#endif

iOS Development-Singleton mode

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.