如何像常量一样声明我自己的CGRectZero? [英] How to declare my very own CGRectZero like constant?

查看:210
本文介绍了如何像常量一样声明我自己的CGRectZero?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个新手C/Objective-C问题:-)

This is a newbie C/Objective-C question :-)

假设我要一个CGRectOne和CGRectTwo常量.

Let say I want a CGRectOne and a CGRectTwo constants.

我该如何宣布呢?

谢谢, 杰里米

推荐答案

其他答案很好-在某些情况下-.

A)声明为static时,每次翻译都会发出一个副本.如果只对一种翻译可见(即其定义在您的 .m/ .c文件中),那很好.否则,您最终会在每次翻译中得到副本,其中包括/导入具有静态定义的标头.这会导致二进制文件膨胀,并增加构建时间.

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 = {...};将在它声明的范围内发出一个符号.如果该标题恰好是多个翻译可见的标头,则将导致链接错误(因为多次定义了CGRectOne,例如,每个 .c/ .m文件直接或间接定义了一次)包括定义常量的标头).

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 (because CGRectOne is defined multiple times -- e.g. once per .c/.m file which directly or indirectly includes the header where the constant is defined).

现在,您知道在其中使用这两个声明的上下文了,让我们介绍一下extern方式. extern方法允许您:

Now that you know the context to use those 2 declarations in, let cover the extern way. The extern way allows you to:

  • 在标头中声明常量
  • 在许多翻译中使用常量
  • 同时发出常数的一个精确定义

extern方法非常适合在多个文件之间重用常量.这是一个示例:

The extern approach is ideal for reusing the constant among multiple files. Here's an example:

File.h

// the declaration in the header:
extern const CGRect CGRectOne;

File.c/m

// the definition:

#import "File.h"

const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };


注意:省略const只会使其成为全局变量.


Note: Omitting the const would just make it a global variable.

这篇关于如何像常量一样声明我自己的CGRectZero?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆