Where do I have to declare static variables?

后端 未结 3 790
臣服心动
臣服心动 2021-01-02 16:09

i.e. I want to bring this in my code:

static BOOL MyConstantBool = YES;

Must it be before or after @implementation? Are there rules where t

相关标签:
3条回答
  • 2021-01-02 16:28

    If it's after the @implementation block, then you can't use it in the @implementation block (unless it's been forward declared somewhere else using extern). Here's how I do it:

    //Constants.h
    extern BOOL MyConstantBool;
    extern NSString* MyConstantString;
    
    
    //Constants.m
    #import "Constants.h"
    BOOL MyConstantBool = YES;
    NSString* MyConstantString = @"Hello, world!";
    
    
    //SomeOtherFile.m
    #import "Constants.h" 
    //you can now use anything declared in Constants.h 
    
    0 讨论(0)
  • 2021-01-02 16:41

    Globals can go pretty much wherever you want; just put it in whatever place makes sense stylistically. I prefer to see globals near the top of source files, personally.

    While you could put the definition into a header file, I don't recommend it. Putting any kind of definition in a header file can lead to multiply-defined symbol linker errors on down the road. If you need more than one compilation unit to see the variable, you can't make it static anyway - you'll need to define it in an implementation file somewhere and use extern to make it visible amongst various source files.

    0 讨论(0)
  • 2021-01-02 16:46

    If you want to define a global variable, it does not matter where you put it (inside or outside of @implementation). In this context, static means that the variable is only visible from within this compilation unit (.m file).

    There are also static variables, which are defined in functions. They work like global variables, but are visible only from within the function's scope.

    0 讨论(0)
提交回复
热议问题