gpt4 book ai didi

ios - 类方法中的static关键字是什么意思

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

刚刚阅读 Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC? ,我找到了 Apple 推荐的让单例看起来非常酷和整洁的答案和方法,但经过进一步思考,我想知道,类方法中的 static 关键字在 Objective-c 中到底意味着什么?在 Apple 推荐这种模式之前,我只遇到过 static 作为类字段的修饰符。在类方法中使用 static 时行为如何变化?

 + (MyClass *)sharedInstance
{
// Static local predicate must be initialized to 0
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}

最佳答案

在这种情况下,它是 C 语言构造*,表示静态局部变量。静态局部变量在整个程序执行过程中保持其内存单元。实际上,这意味着一旦为变量分配了一个值,它就会在后续的函数调用中保留该值。所以它就像一个缓存。

您还可以看到它在 Objective-C 中使用了很多 NSDateFormatter。实例,因为这些创建起来很昂贵,所以你只想做一次,然后重用同一个实例。

  • 见:http://en.wikipedia.org/wiki/Static_(keyword)

  • * 请记住,Objective-C 是 C 的超集。

    关于ios - 类方法中的static关键字是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26490301/

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