版本:iOS13.5
once.h
索引
- 只能执行一次block
dispatch_once
- 只能执行一次function
dispatch_once_f
详解
- 只能执行一次block
void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block);
predicate 指向dispatch_once_t的指针,该指针用于测试block是否已完成
必须将其初始化为0。一般为静态和全局变量,因为它们默认为0
block 只执行一次的块typedef void (^dispatch_block_t)(void);
例:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
- 只能执行一次function
void dispatch_once_f(dispatch_once_t *predicate, void *_Nullable context,
dispatch_function_t function);
function typedef void (*dispatch_function_t)(void *_Nullable);
返回值是void,参数是void *的函数指针
context 类型为void *,函数function的参数
与dispatch_once
区别就是一个执行block 一个执行可带参数的function
例:
static dispatch_once_t onceToken;
int num = 10;
dispatch_once_f(&onceToken, &num, function);
NSLog(@"%d", num);
void function(void *num) {
int *adress = num;
*adress = 20;
}
用法
常用于单例创建 其中dispatch_once效率更高
单例1:
+ (instancetype)shareInstance {
static Class *_instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
单例2:
+ (instancetype)shareInstance {
static Class *_instance = nil;
@synchronized (self) {
if (!_instance) {
_instance = [[self alloc] init];
}
}
return _instance;
}
单例3:
static dispatch_semaphore_t semaphore = nil;
+ (void)initialize {
if (!semaphore) {
semaphore = dispatch_semaphore_create(1);
}
}
+ (instancetype)shareInstance {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
static Class *_instance = nil;
if (!_instance) {
_instance = [[self alloc] init];
}
dispatch_semaphore_signal(semaphore);
return _instance;
}
网友评论