Explain the use of IOS macro and constant (define, const)

Time:2021-1-12

Xiao Bian has sorted out the correct usage of macro (define) and constant (const) in IOS for you, which will help you understand this aspect more deeply.

When we want to share some data globally, we can use macro, variable and constant

Macro:

#Define hscoder @ “Hans ha ha”

Variables:

Nsstring * hscoder = @ “Hans hahaha”;

Constant:

Four ways of writing:
Static const nsstring * hscoder = @ "Hans hahaha";
Const nsstring * hscoder = @ "Hans hahaha";
Nsstring const * hscoder = @ "Hans hahaha";
Nsstring * const hscoder = @ "Hans hahaha";

Different positions of const indicate different meanings

Nsstring const * is different from nsstring * const in that the former means that the content pointed by the pointer cannot be modified, while the latter means that the pointer itself cannot be modified

Sometimes you will encounter:

Const nsstring * will encounter an alert:

Change it to nsstring * const. It shows that the two are different.

Thinking: macro and constant / variable selection?

Macro: just text replacement in preprocessor, no type, no type check, compiler can optimize the same string. Save only one copy to the. Rodata section. Even strings with the same suffix can be optimized. You can compile and test “Hello world” and “world” with GCC, and only store the first one. When fetching, you only need to give the front and middle addresses. If it is integer or floating-point, there will be multiple copies, but these numbers are written in the instruction. It’s just a code segment. Using a lot of macros will make the binary file bigger

Variable: share a piece of memory space. Even if it is used in n places in the project, n pieces of memory space will not be allocated. It can be modified and type checking will be performed in the compilation phase

Constant: share a piece of memory space. Even if it is used in n places in the project, n pieces of memory space will not be allocated. You can set whether it can be modified according to the position modified by const. Type checking will be performed in the compilation phase

Constant distinction

Global constant: no matter what folder you define, it can be accessed from outside

Const nsstring * hscoder = @ “Hans hahaha”;

For example:

Local constant: after being modified with static, it cannot provide external access

Static const nsstring * hscoder = @ “Hans hahaha”;

In general projects, global constants are defined and written in a separate file

For example: