dispatch_once 文档中的 "Always call this function before using or testing any variables that are initialized by the block." 是什么意思?
dispatch_once what means "Always call this function before using or testing any variables that are initialized by the block." in documentation?
Apple 文档 [1]
https://developer.apple.com/reference/dispatch/1447169-dispatch_once
在 "Discussion" 部分说:
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.
下面的短语是什么意思?
Always call this function before using or testing
any variables that are initialized by the block.
当我必须遵守此要求时,您能否展示简短的代码示例?
我的想法:
这与以下示例中的块无关:
+(instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
因为我不能(肯定)使用 sharedInstance
在调用 dispatch_once
之前由块初始化。因为dispatch_once
调用这个块!那么 Apple 文档警告我们的障碍是什么?
这只是意味着,如果您在传递给 dispatch_once
的块中初始化 sharedInstance
,您需要确保在访问 sharedInstance
之前调用 dispatch_once
第一次。换句话说,如果您访问任何由 dispatch_once
首次设置的变量,您读取的值可能未初始化。
Apple 文档 [1] https://developer.apple.com/reference/dispatch/1447169-dispatch_once 在 "Discussion" 部分说:
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.
下面的短语是什么意思?
Always call this function before using or testing any variables that are initialized by the block.
当我必须遵守此要求时,您能否展示简短的代码示例?
我的想法: 这与以下示例中的块无关:
+(instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
因为我不能(肯定)使用 sharedInstance
在调用 dispatch_once
之前由块初始化。因为dispatch_once
调用这个块!那么 Apple 文档警告我们的障碍是什么?
这只是意味着,如果您在传递给 dispatch_once
的块中初始化 sharedInstance
,您需要确保在访问 sharedInstance
之前调用 dispatch_once
第一次。换句话说,如果您访问任何由 dispatch_once
首次设置的变量,您读取的值可能未初始化。