gpt4 book ai didi

ios - iOS 中的单例

转载 作者:行者123 更新时间:2023-12-01 17:34:01 26 4
gpt4 key购买 nike

我试图理解为什么在重复调用 sharedInstance 时 dinpatch_once_t 和 _sharedObject 没有分别设置为 0 和 nil 的原因。在我看来,这是编码的方式,局部变量将被重新初始化,因为你可以重置一个静态值,对吧?我在这里不了解 ARC 或 iOS 内存管理的哪些基础知识?

+ (id)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;

// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;

// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});

// returns the same object each time
return _sharedObject;
}

最佳答案

它实际上是 C 的东西,而不是 ARC 或 iOS。它是一个“内部静态变量”(又名局部静态变量),它的声明只被处理一次。它具有该功能的本地范围,但使用生命周期更长。

关于ios - iOS 中的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com