每天学习一个API:GCD - dispatch_once

97652-f57468063bee5568.jpeg
每天学习一个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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值