美文网首页
每天学习一个API:GCD - dispatch_once

每天学习一个API:GCD - dispatch_once

作者: TimBao | 来源:发表于2016-09-07 13:07 被阅读27次
    每天学习一个API

    官方定义:Executes a block object once and only once for the lifetime of an application. 在应用程序的生命周期内执行一个block对象一次且仅仅执行一次

    • 函数声明:
    
    void dispatch_once(dispatch_once_t*predicate, dispatch_block_tblock);
    
    
    • 参数说明:

    predicate:A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not. 一个指向结构体dispatch_once_t的指针,用于检测block是否完成。

    block:The block object to execute once. 执行一次的block对象。

    • 详细说明:

    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.

    该API用于在应用中初始化全局或者单例对象。在使用block中声明的变量之前,总是需要调用这个接口。
    多线程同时调用这个接口的时候,会进行同步等待指导block完成。
    predicate参数必须指向全局变量或者静态变量。如果使用automatic或者动态分配变量的话,会发生不可预测的问题。

    • 示例展示:
    @interface UCARDataStorageManager : NSObject
    
    + (instancetype)shareInstance;
    
    @end
    
    @implementation UCARDataStorageManager
    
    + (instancetype)shareInstance
    {
        static UCARDataStorageManager* instance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[UCARDataStorageManager alloc] init];
        });
        return instance;
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:每天学习一个API:GCD - dispatch_once

          本文链接:https://www.haomeiwen.com/subject/lgejettx.html