我有一个用于存储其他类的实例对象的类。这个类有以下类方法被称为每当我需要得到的类本身(和存储其他类的实例,其方法是对数据结构进行操作的数据结构):Objective C中的静态初始化C
+ (instancetype)sharedStore
{
static BNRItemStore *sharedStore = nil;
//Do I need to create a sharedStore?
if (!sharedStore) {
sharedStore = [[self alloc] initPrivate];
}
return sharedStore;
}
的static BNRItemStore *sharedStore = nil;
行对我来说非常混乱。第一次调用类方法时,我们声明static BNRItemStore *sharedStore
并将其设置为nil
。我不明白为什么如果我们第二次调用该方法,sharedStore
不会被覆盖和/或释放。显然,这种情况从未发生过,所有后续调用+ (instancetype)sharedStore()
方法似乎都完全忽略了static BNRItemStore *sharedStore = nil;
这一行。这是为什么?
这是因为四十年的静态变量规则。初始化发生_once_。 – gnasher729