Characteristics and implementation of singletons in Objective-C

One sentence to introduce singletons: Throughout the entire program, no matter when and in which class an object is created, the object obtained when it is created is always the same object.

Characteristics of singleton :

1. Since objects created in different locations return the same object, the singleton mode can be used as a shared object for the entire program, and any module can operate and access the properties of the singleton object at any time.

2. Some people say that macro definitions can also be shared globally. However, another important feature of singletons is that during the running of the program, the attributes of the singleton object can be modified according to actual needs. Once the macro definition is defined, it cannot be modified during the entire running of the program.

Singleton implementation ideas:

When creating an object in Objective-C, the alloc method is called. When the system calls the allco method, the following method is called

+ (id)allocWithZone:(NSZone *)zone

We can override the class method of the singleton object and return the only existing object through judgment within the method.

The specific implementation code is as follows:

+ (id)allocWithZone:(NSZone *)zone {
    static id instance = nil;
    if (instance == nil) {
        instance = [super allocWithZone:zone];
    }
    return instance;
}

The above code simply implements a singleton, but for multi-threaded access, some protective code needs to be added. This will be discussed later in the multi-threading section.

Some specifications for singletons:

Under normal circumstances, each singleton should create a class method for easy call and use. The naming convention for methods is:

+ (instancetype)shareClass;

+(instancetype)defaultClass;

In the method implementation, directly return [self new];

Okay, this is the simplest way to implement a singleton. After mastering these basic ideas, think about it, what problems will occur when using a singleton with multiple threads?

Guess you like

Origin blog.csdn.net/JustinZYP/article/details/124204307