如何在 Objective-C 中声明静态变量? [英] How to declare static variables in Objective-C?
本文介绍了如何在 Objective-C 中声明静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我们如何将静态变量声明为 Objective C 类的一部分?我想让它跟踪我用这个类创建的实例数量.
Can someone tell how we can declare a static variable as part of a Objective C class? I wanted this to track the number of instances I am creating with this Class.
推荐答案
使用您班级的 +initialize
方法:
Use your class's +initialize
method:
@implementation MyClass
static NSUInteger counter;
+(void)initialize {
if (self == [MyClass class]) {
counter = 0;
}
}
@end
(更新为添加 if (self == [MyClass class])
条件,如评论中建议的那样.)
(Updated to add if (self == [MyClass class])
conditional, as suggested in comments.)
这篇关于如何在 Objective-C 中声明静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文