Objective-C 静态修饰符?
如何在 Objective-C 类中创建静态变量?我熟悉在头文件中使用 @private 作为私有变量,但我试图创建一个访问静态变量的静态方法。我应该如何在头文件中声明这个静态变量?
How do I create a static variable in my Objective-C class? I'm familiar with using @private in my header files for private variables, but I am trying to create a static method which accesses a static variable. How should I declare this static variable in my header file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Objective-C 在这方面简单地遵循 C——创建静态文件变量。在您的实现(即您的 .m 文件)中,在任何地方放置一个声明(但理想情况下是在文件顶部的合理位置,或者如果仅在一个地方访问它,甚至在相关方法中)。
如果您想提供对此类静态的受控访问,请将其放在任何方法实现之外,并使用类方法来访问它。
Objective-C simply follows C in this regard - you make static file variables. In your implementation (ie your .m file) put a declaration anywhere (but ideally somewhere sensible like at the top of the file, or even in the relevant method if it's only accessed in one place).
If you want to provide controlled access to such a static, put it outside of any method implementation, and use class methods to access it.
Objective-C 的静态变量遵循与 C 中的静态变量相同的规则(存储修饰符)。您可以在文件或函数范围内声明静态变量,但它们与实例变量一样与您的类没有关系。
Static variables for Objective-C follow the same rules for static variables in C (storage modifier). You can declare your static variables at file or function scope but they have no relation to your class like instance variables do.
Objective-C 没有静态类变量。但是,您可以创建模块静态变量(就像在 C 中一样)。要拥有私有静态变量:
将给出 MyStatic 模块级作用域。因为这只是 C,所以没有办法使 MyStatic 从例如 MyClass 上的类别可见,而不通过
extern
声明使其公开可见。由于静态变量实际上是全局变量,这可能是一件好事 - MyClass 应该尽其所能来隐藏MyStatic
的存在。如果您希望静态变量是公共的(您真的不想):
Objective-C doesn't have static class variables. You can create module-static variables (just as in C), however. To have a private, static variable:
will give
MyStatic
module-level scope. Because this is just C, there's no way to make MyStatic visible from, e.g. categories on MyClass without making it publicly visible via anextern
declaration. Since static variables are effectively global variables, this is probably a good thing—MyClass should be doing absolutely everything it can to hide the existence ofMyStatic
.If you want the static variable to be public (you really don't want to):