How to declare my very own CGRectZero like constant?

前端 未结 4 1683
失恋的感觉
失恋的感觉 2021-01-31 18:54

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

4条回答
  •  野性不改
    2021-01-31 19:41

    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 (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).

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

    • declare the constant in a header
    • use the constant in many translations
    • while emitting exactly one definition of the constant

    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 } };
    

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

提交回复
热议问题