iOS学习笔记6-单例理解

单例小结:以下是官方文档安全

Declarationapp

void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);this

Parametersspa

predicate       线程

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

block  orm

The block object to execute once.对象

Discussionip

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()
    }()
相关文章
相关标签/搜索