ARC (automatic memory management) under the implementation of singleton mode

preface

During development, you encounter a situation where a class needs to be used several times, and a new memory address is allocated for each creation. However, in some cases this is not necessary.

If you play music, you don’t usually say, open a player to play multiple songs at the same time.

Moreover, the resources of the system are limited, especially for mobile devices. So the singleton pattern came into being.

Introduction to the

Singleton pattern: During program execution, there is only one instance of a class. And the instance is easy to use by outsiders. In other words, no matter how many times a class is created, storage is allocated only once.

purpose

To save system resources, a shared resource is initialized only once and storage space is allocated only once during program running.

benefits

Saves system resources.

Implementation steps

Take the PDuser class as an example

1. Define static variables and store unique instances

static PDuser *_instance;
Copy the code

This way, the instance variable is not available outside of the file, only in this file.

2. Rewrite the allocWithZone method with dispatch_once and call the super allocWithZone method

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}
Copy the code

This step can also be done in lazy loading mode:

+ (instancetype)allocWithZone:(struct _NSZone *)zone { @synchronized(self) {if (_instance == nil) {_instance = [super allocWithZone:zone]; } } return _instance; }Copy the code

3. Implement class methods

+(instancetype)shareUser{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
Copy the code

New method: allocates and initializes memory

Alloc: allocates memory for an object, init: initializes properties in an object, etc

4, external call method provides a class method, get singleton object, easy to create. + (instancetype)shareUser;

At this point, the basic singleton has been implemented. Now we can continue to improve.


(Optional) To make the singleton more serious, override copy and mutableCopy if you want to support copy. Just return the variable, because you can’t use the copy method until you’ve created the object.

<NSCopying, NSMutableCopying>

- (id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}
Copy the code

6. The initial value of dispatch_once_t is 0L. Reset the dispatch_once_t parameter and the instance parameter.

Provide class methods to the outside world

+(void)releaseInstance{ _instance = nil; onceToken = 0l; // Set the static variable pointer of the static store to nil, so that the singleton is reclaimed by the system without any pointer to it. }Copy the code
  • Note: Classes designed using the singleton pattern are not inheritable!

Singleton naming format

It involves the question of naming, what is the norm? Common singleton names are share, share + class name, default, and default + class name

Applicable scenario

Throughout the program, the same resource can be shared — it only needs to be created, initialized and allocated once. For example: user instance, file manager, etc.

test

Create 3 objects

    PDuser *user1 = [PDuser shareUser];
    PDuser *user2 = [PDuser shareUser];
    PDuser *user3 = [PDuser shareUser];
    NSLog(@"user1:%@\nuser2:%@\nuser3:%@",user1,user2,user3);
Copy the code

The results ofsuccessful

Macro definition

To implement singleton code reuse, you cannot use inheritance. Use macros to extract the singleton pattern.

Create a new.h file single.h that contains two parts, the.h and.m parts

Change the specific class type to ID type, and set the parameter (name) class name, with ## connection, when used, the outside class can flexibly change. In addition, the code in.m is concatenated with multiple “” signs.

External use:

In the.h of a newly created class, note the class name as an argument

. In the m

Can be

The relevant data

www.jianshu.com/p/5226bc8ed…