iOS中的单例
我试图理解为什么在多次调用sharedInstance时,dinpatch_once_t和_sharedObject没有分别设置为0和nil。在我看来,按照这种编码方式,局部变量将被重新初始化,因为你可以重置一个静态值,对吗?我在这里不了解ARC或iOS内存管理的哪些基础知识iOS中的单例,ios,singleton,Ios,Singleton,我试图理解为什么在多次调用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
+ (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。它是一个“内部静态变量”(也称为局部静态变量),其声明只处理一次。它的作用域是函数的局部作用域,但使用寿命延长。它实际上是一个C对象,而不是ARC或iOS。它是一个“内部静态变量”(也称为局部静态变量),其声明只处理一次。它具有功能的局部范围,但使用寿命延长