开发者

Where do I have to declare static variables?

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

static BO开发者_如何学JAVAOL MyConstantBool = YES;

Must it be before or after @implementation? Are there rules where to place that? Can it also go into the header file?


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.


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 


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜