OC write singleton like this

Singleton mode is a commonly used software design mode. In its core structure, it only contains a special class called a singleton. The singleton pattern can ensure that there is only one instance of a class in the system. That is, a class has only one object instance. The role of most singleton models is probably to share information and manage the center. Singleton can also be used in passing value.

In the development process, we often use some singletons of the system:

  1. [UIApplication sharedApplication]: a symbol of an application, a UIApplication object represents an application
  2. [NSNotificationCenter defaultCenter]: Notification
  3. [NSUserDefaults standardUserDefaults]: A way of system localization storage
  4. [NSFileManager defaultManager]: File operations

1. The simple way

The simplest scenario singleton method in OC

 static Person *p = nil ;
+(instancetype)sharePerson{
    if(p == nil){
        p = [[Person alloc]init];
    }
    return p;
}

Create a static pointer; if the pointer does not point to an object, create an object and let the pointer hold the object; finally return the object held by the pointer. Because it is static, the object held by the pointer will not be released, which guarantees that only one object will be returned each time this method is called. This achieves the purpose of singleton, but it is not recommended to write in this way, in a multithreaded environment. Writing is not guaranteed to be thread safe

2. Object locking

Use keywords to lock objects to ensure thread safety. This is one of the singleton implementation methods recommended by Apple


+(instancetype)defaultPerson{
	static Person *p = nil;
    @synchronized (self) {
        if (p == nil) {
            p = [[Person alloc]init];
        }
    }
    return p;
}

This code can only be executed in a queue, which perfectly guarantees that the singleton has only one object.

noteMutex locks are related to multi-thread concurrency. The basic meaning is that multiple threads access the same piece of code at the same time. They must be executed in order and cannot be concurrent. This can effectively solve the safety problem of multithreading.

I did only execute the above method once, but when I use this method for the second time, the if statement still needs to go? After everyone has created the objects, they still queue up little by little, which affects efficiency too much. Therefore, as a developer, things that consume thread resources and perform inefficiently are not allowed to happen. Here comes a better way.

3.GCD

Use GCD dispatch_once to ensure that the code of the scene object is only executed once during the entire program running

+(instancetype)sharePerson{
	static Person *p = nil ;//1.声明一个空的静态的单例对象
    static dispatch_once_t onceToken; //2.声明一个静态的gcd的单次任务
    dispatch_once(&onceToken, ^{ //3.执行gcd单次任务:对对象进行初始化
        if (p == nil) {    
            p = [[Person alloc]init];
        }
    });
  return p;
}

note Dispatch_once is an object in GCD. This function can ensure that no matter how many times it is called, the internal block will only be executed once to ensure the uniqueness of code execution.

In summary, the singleton method used by OC is generally of these three, and we generally use the third one, which has higher security and better execution efficiency.

Guess you like

Origin blog.csdn.net/zjpjay/article/details/86487777