ios– single-case mode it's enough to write once.

Source: Internet
Author: User

I. Introduction to the SINGLETON model

    1. The role of the singleton pattern
      You can guarantee that there is only one instance of a class when the program is running, and that the instance is easy for outside access
      Thus conveniently control the number of instances, and save system resources
    2. The use of single-case mode
      In the entire application, share a resource (this resource only needs to be initialized 1 times) and is typically used for tool classes. For example: Login controller, network data request, music player, etc. a project needs to use multiple controllers or methods.
    3. Advantages and disadvantages of a singleton model
      Advantages:
      The singleton mode can guarantee that there is only one instance of a class in the system, and the instance is easy to be accessed, thus it is convenient to control the number of instances and save system resources.
      Singleton mode is the best solution if you want to have only one object for a class in the system.
      Singleton mode because classes control the instantiation process, classes can be more flexible in modifying the instantiation process.

      Disadvantages:
      Once a singleton object is established, the object pointer is stored in the static area, and the memory space allocated by the Singleton object in the heap is not released until the application terminates.
      The Singleton class cannot be inherited, so it is difficult to extend the class.
      The singleton does not apply to changing objects, and if objects of the same type are always changed in different use case scenarios, the singleton can cause data errors and cannot save each other's state.

Note: Before we use the Singleton class, we must consider the suitability of the Singleton class and the extensibility of the class, so as to avoid blindly abusing the single case

Two. The implementation of the single case in arc

Single-instance implementation steps in Arc

1 provides a static modified global variable inside the class
2 provides a class method for easy access to the outside world
3 Overriding the +allocwithzone method to ensure that only one memory space is allocated once for a single object
4 for rigor, rewrite the-copywithzone method and the-mutablecopywithzone method

Single example code implementation in Arc

#import "Tools.h" @implementationTools//creating static objects to prevent external accessStaticTools *_instance;+ (Instancetype) Allocwithzone: (struct_nszone *) zone{//@synchronized (self) {//        //To prevent multi-threaded access to objects at the same time, resulting in multiple allocation of memory space, so add the thread lock//if (_instance = = nil) {//_instance = [Super Allocwithzone:zone];//        }//return _instance;//    }    //You can also use a one-time code    Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{        if(_instance = =Nil) {_instance=[Super Allocwithzone:zone];    }    }); return_instance;}//to make an instance easy to access outside we generally provide a class method//class method naming specification Share class name |default class name | class name+(instancetype) sharetools{//return _instance; //the best thing to do with self is to use tools to invoke his child class when an error occurs    return[[Self alloc]init];}//To be rigorous, rewrite Copywithzone and Mutablecopywithzone.-(ID) Copywithzone: (Nszone *) zone{return_instance;}-(ID) Mutablecopywithzone: (Nszone *) zone{return_instance;}
Three. The implementation of the single case in MRC

MRC Single-instance implementation steps

1 provides a static modified global variable inside the class
2 provides a class method for easy access to the outside world
3 Overriding the +allocwithzone method to ensure that only one memory space is allocated once for a single object
4 for rigor, rewrite the-copywithzone method and the-mutablecopywithzone method
5 Overriding the release method
6 overriding the Retain method
7 We recommend that you return a maximum value in the Retaincount method

Configuring the MRC Environment

1 Note that arc is not a garbage collection mechanism, it is a compiler feature
2 Configuring the MRC Environment: Build setting, search automatic ref-> Modify to N0

Single example code implementation in MRC
After configuring the MRC environment, rewrite the following three methods on an ARC code basis

void ) release{}-(instancetype) retain{    return  _instance;} -(Nsuinteger) retaincount{    return  maxfloat;}
Four. Once and for all, the optimization of the singleton mode

If we want to be once and for all, we will face two problems
1: How do I write a single sample code that works in both arc and MRC environments?
2: How to make a single sample code can be used together with multiple classes
In order to solve these two problems, we can use the generation parameter in the PCH file to compile the macro and conditional
Use conditional compilation to determine whether an arc or MRC environment

12345 #if __has_feature (OBJC_ARC) //If it is arc, then execute the code here 1 #else //If it is not arc, then execute the Agent code 2 #endif

Note: The singleton mode cannot use inheritance because inheritance is used, and static variables are inherited, and only one instance object is created when the child and parent classes are created at the same time.
No more nonsense, just on the code.
PCH file Single.h

#defineSingleh (name) + (instancetype) share# #name;#if__has_feature (OBJC_ARC)#defineSinglem (name) static ID _instance;+ (instancetype) Allocwithzone: (struct_nszone *) zone{Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];    }); return_instance;}+(instancetype) share# #name {return[[Self alloc]init];}-(ID) Copywithzone: (Nszone *) zone{return_instance;}-(ID) Mutablecopywithzone: (Nszone *) zone{return_instance;}#else#defineSinglem static ID _instance;+ (instancetype) Allocwithzone: (struct_nszone *) zone{Staticdispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];});return_instance;}+(instancetype) sharetools{return[[Self alloc]init];}-(ID) Copywithzone: (Nszone *) zone{return_instance;}-(ID) Mutablecopywithzone: (Nszone *) zone{return_instance;}-(OneWayvoid) release{}-(instancetype) retain{return_instance;}-(Nsuinteger) retaincount{returnmaxfloat;}#endif


We can then once and for all, in any project, when we want to use a singleton class, just import the PCH file into the project and
Called in the. h filesingleH(类名)
Called in the. m filesingleM(类名)

The method is called share类名 directly when the class is created.

ios– single-case mode it's enough to write once.

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.