Objective-C 头文件中的常量是如何初始化的?
如何在头文件中初始化常量?
例如:
@interface MyClass : NSObject {
const int foo;
}
@implementation MyClass
-(id)init:{?????;}
How do you initialise a constant in a header file?
For example:
@interface MyClass : NSObject {
const int foo;
}
@implementation MyClass
-(id)init:{?????;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于“公共”常量,您可以在头文件 (.h) 中将其声明为
extern
并在实现文件 (.m) 中对其进行初始化。然后
考虑使用
enum
如果它不仅仅是一个,而是多个属于在一起的常量For "public" constants, you declare it as
extern
in your header file (.h) and initialize it in your implementation file (.m).then
Consider using
enum
if it's not just one, but multiple constants belonging togetherObjective C 类不支持常量作为成员。您无法按照您想要的方式创建常量。
声明与类关联的常量的最接近方法是定义返回该常量的类方法。您还可以使用 extern 直接访问常量。两者都在下面进行了演示:
类方法版本的一个优点是它可以很容易地扩展以提供常量对象。您可以使用外部对象,但必须在初始化方法中初始化它们(除非它们是字符串)。所以你经常会看到以下模式:
Objective C classes do not support constants as members. You can't create a constant the way you want.
The closest way to declare a constant associated with a class is to define a class method that returns it. You can also use extern to access constants directly. Both are demonstrated below:
An advantage of the class method version is that it can be extended to provide constant objects quite easily. You can use extern objects, nut you have to initialise them in an initialize method (unless they are strings). So you will often see the following pattern:
对于像整数这样的值类型常量,一个简单的方法是使用 枚举 hack正如unbeli所暗示的那样。
与使用 extern 相比,它的一个优点是它在编译时全部解析,因此不需要内存来保存变量。
另一种方法是使用 static const 来替代 C/C++ 中的 enum hack。
快速浏览 Apple 的标头表明,枚举 hack 方法似乎是 Objective-C 中执行此操作的首选方法,而且我实际上发现它更干净并自己使用它。
另外,如果您要创建选项组,您应该考虑使用
NS_ENUM
来创建类型安全常量。有关
NS_ENUM
及其同类NS_OPTIONS
的更多信息,请访问 NSHipster 。A simple way for value type constants like integers is to use the enum hack as hinted by unbeli.
One advantage to this over using
extern
is that it's all resolved at compile time so there no memory is needed to hold the variables.Another method is to use
static const
which is what was to replace the enum hack in C/C++.A quick scan through Apple's headers shows that the enum hack method appears to be the preferred way of doing this in Objective-C and I actually find it cleaner and use it myself.
Also, if you are creating groups of options you should consider using
NS_ENUM
to create a typesafe constants.More info on
NS_ENUM
and it's cousinNS_OPTIONS
is available at NSHipster.