iOS学习笔记6-单例理解

单例小结:如下是官方文档

Declaration

void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);

Parameters

predicate       

A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.

block  

The block object to execute once.

Discussion

This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.

 

If called simultaneously from multiple threads, this function waits synchronously until the block has completed.


The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

小结:

  1. 使用dispatch_once方法可以创建单例或者某些初始化动作时使用,以保证其唯一性,

  2. 该方法是线程按钮的,所以请放心大胆的在子线程中使用(前提是你的dispatch_once_t *predicate 对象一定是在全局或者静态对象,如果不是,那结果不可预知




OC中单例的写法

+ (instancetype)sharedTools {
    static id instance;
    
    static dispatch_once_t onceToken;
    
    NSLog(@"---> %ld",onceToken);
    
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

Swift中单例的写法

单例的写法和懒加载很像,静态区的对象只能设置一次数值,第一次使用时才创建对象

    static let sharedTools2: SoundTools = {
        print("wwwwwwww")
        
        return SoundTools()
    }()


你可能感兴趣的:(iOS学习笔记6-单例理解)