全局常量文件中的 Objective-C typedef 枚举
好的,这与问题“Objective C 中的常量”有关。
我创建了 Constants.h 及其相应的 Constants.m 文件:
// Constants.h
extern int const BOOKS;
typedef enum SSDifficultyLevel {
EASY = 0,
MEDIUM = 1,
HARD = 2
} SSDifficultyLevel;
// Constants.m
int const BOOKS = 66;
我的问题:enum
可以是 typedef在Constants.h中?代码编译良好(到目前为止没有警告或错误),但我想知道这是否是正确的方法,因为相关问题中提供的解决方案涉及拆分常量的定义和声明。
谢谢。
OK, this is related to question "Constants in Objective C".
I created Constants.h and its corresponding Constants.m file:
// Constants.h
extern int const BOOKS;
typedef enum SSDifficultyLevel {
EASY = 0,
MEDIUM = 1,
HARD = 2
} SSDifficultyLevel;
// Constants.m
int const BOOKS = 66;
My question: Is OK for the enum
to be typedef
'd in Constants.h? The code is compiling fine (no warnings or errors so far) but I was wondering if this is the right way to do it, as the solution provided in the related question involves splitting the constant's definition and declaration.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,常量和枚举有不同的用途(尽管有一些明显的重叠)。所以,不要离人们的期望太远,除非你有充分的理由打破这条规则。
就我个人而言,我不太喜欢“全局常量标头”,因为您通常应该将这些声明与它们的使用对象相关联。例如,Apple 的框架通常在它们相关的接口附近声明枚举,并在与类相同的标头中声明通知名称。
除此之外,你已经正确地声明了事情。
如果您使用 c++ 或 objc++,那么您将需要修复该 extern,因为名称可能不同,这可能会导致链接错误。
像这样的东西应该可以解决问题:
然后你可以像这样声明
BOOKS
:另一个注释,这可能只是为了在你的示例中进行说明:这些标识符非常短,很容易导致冲突与其他标识符。
well, a constant and an enum serve different purposes (although there is some obvious overlap). so, just don't go too far from what people would expect, unless you have a really good reason to break that rule.
personally, i don't like the "global constants header" much, as you should usually associate those declarations with what they are used with. for example, Apple's frameworks typically declare the enums near the interfaces they relate to, and the notification names in the same header as the class.
other than that, you have declared things correctly.
if you use c++ or objc++, then you will want to fix that
extern
because the names may differ, and that can result in link errors.something like this should do the trick:
then you would declare
BOOKS
like so:one other note, and this may have been only for illustration in your example: those identifiers are very short, and can easily cause collisions with other identifiers.