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()
    }()
相關文章
相關標籤/搜索