如何像常量一样声明我自己的 CGRectZero?
这是一个新手 C/Objective-C 问题:-)
假设我想要一个 CGRectOne 和一个 CGRectTwo 常量。
我该如何声明呢?
谢谢, 杰里米
This is a newbie C/Objective-C question :-)
Let say I want a CGRectOne and a CGRectTwo constants.
How can I declare that?
Thanks,
Jérémy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
其他答案都很好 -在某些情况下-。
A) 将其声明为
static
将在每次翻译时发出一个副本。如果它对一个翻译可见(即它的定义位于您的 .m/.c 文件中),那就没问题了。否则,您最终会在每个翻译中得到包含/导入具有静态定义的标头的副本。这可能会导致二进制文件膨胀,并增加构建时间。B)
const CGRect CGRectOne = {...};
将在其声明的范围内发出一个符号。如果这恰好是多个翻译可见的标头,您最终会出现链接错误(因为CGRectOne
被定义了多次 - 例如每个 .c/.m 一次文件直接或间接包含定义常量的标头)。现在您已经知道了使用这两个声明的上下文,让我们介绍一下 extern 方式。
extern
方式允许您:extern
方式非常适合重用该常量多个文件之间。下面是一个示例:File.h
File.c/m
注意:省略
const
只会使其成为全局变量。The other answers are fine -in some cases-.
A) declaring it
static
will emit a copy per translation. That is fine if it is visible to exactly one translation (i.e. its definition is in your .m/.c file). Otherwise, you end up with copies in every translation which includes/imports the header with the static definition. This can result in an inflated binary, as well as an increase to your build times.B)
const CGRect CGRectOne = {...};
will emit a symbol in the scope it is declared. if that happens to be a header visible to multiple translations you'll end up with link errors (becauseCGRectOne
is defined multiple times -- e.g. once per .c/.m file which directly or indirectly includes the header where the constant is defined).Now that you know the context to use those 2 declarations in, let cover the
extern
way. Theextern
way allows you to:The
extern
approach is ideal for reusing the constant among multiple files. Here's an example:File.h
File.c/m
Note: Omitting the
const
would just make it a global variable.有几个选择。使用 C89、
使用 C99,
或
There are a couple of options. With C89,
With C99,
or
像这样的东西
Something like this
这里使用的技术对我来说效果很好: http://www.cocos2d -iphone.org/forum/topic/2612#post-16402
本质上是 Justin 描述的 extern 方法,但它提供了一个非常完整的示例。
另外,StackOverflow 上的这个答案也提供了一个很好的例子:Constants in Objective-C
The technique used here worked well for me: http://www.cocos2d-iphone.org/forum/topic/2612#post-16402
Essentially its the extern method described by Justin, but it provides a pretty full example.
Also, this answer on StackOverflow provides a good example too: Constants in Objective-C