IOS development – single case

Time:2022-5-25

What is a single case, the purpose of a single case?

When a class has only one instance, you need to use a singleton, that is, the class has only one object. This object cannot be released during program operation, and can be used to record data and transfer values

Single case writing format

Common writing

 + (DataHandle *)shareHandle{
     static DataHandle *dataHandle = nil;
     if(dataHandle == nil){
         dataHandle = [[DataHandle alloc]init];
     }
     return dataHandle;
 }

GCD writing

+ (DataHandle *)shareHandle{
    static DataHandle *dataHandle = nil;
    static dispath_ once onceToken;// Lock
    dispath_once(&onceToken,^{
       dataHandle = [[DataHandle alloc]init];
    })
    return dataHandle;
}