How to use global variables in Objective-C?

前端 未结 4 692
谎友^
谎友^ 2020-12-05 10:58

How should I declare a global variable in my Objective-C project?

4条回答
  •  鱼传尺愫
    2020-12-05 11:23

    Traditionally, global variables are declared in a header, and defined in a source file. Other source files only need to know how it is declared to use it (i.e. its type and its name). As long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.

    Somewhere in your header, you would declare a global variable like this:

    extern int GlobalInt;
    

    The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists. It may be defined later or it may not (it is not the compiler's responsibility to ensure it exists, that is the linker's job). It is similar to a function prototype in this regard.

    In one of your source files, you define the GlobalInt integer:

    int GlobalInt = 4;
    

    Now, each file that includes the header will have access to GlobalInt, because the header says it exists, so the compiler is happy, and the linker will see it in one of your source files, so it too will be happy. Just don't define it twice!

    However


    You should consider whether or not this approach is useful. Global variables get messy for a number of reasons (trying to find out exactly where it is defined or declared, threading issues), there is usually not a need for global variables. You should perhaps consider using a singleton approach.

提交回复
热议问题