Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

objective c - Where various variable and method types should be placed in a header

I've noticed that I get compilation errors if I place certain declarations in certain places in my header file. I've put comments into the code as to where I think certain things go; are they correct?

@interface Level : CCNode { 
    //Instance variables?
    PlayBackgroundLayer* playBGLayer;
    PlayUILayer* playUILayer;
    PlayElementLayer* playElementLayer;
}

//Static methods?
+(void) InitLevel: (int) levelNumber;
+(Level*) GetCurrentLevel;

//Property declarations for instance variables?
@property (nonatomic, retain) PlayBackgroundLayer* playBGLayer;
@end

//Static variables?
Level* currentLevel;
PlayTilemapLayer* playTilemapLayer;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instance variables usually don't need to be declared explicitly. They're created when you @synthesize the property. If you do want them, though, the (new) correct place* is at the top of the implementation block:

@implementation Level
{
    PlayBackgroundLayer* playBGLayer;
    PlayUILayer* playUILayer;
    PlayElementLayer* playElementLayer;
}

Those aren't static methods, they're class methods, but, yes, that's where you declare them. Some people like to put @property declarations before the class methods, but that's a matter of opinion. Instance methods go after both of these, although technically speaking the order doesn't matter -- that is, the compiler doesn't care, it's just a matter of readability.

Those top-level variables need to go somewhere other than a header file, though. If you put them there you will get compilation errors because every file that imports the header will appear to be re-declaring storage for those variables, which isn't allowed.

Ususally you put such variables into a .m file. If you want them to only be visible from there, you would use static. If you want them visible from other files that import the header, you leave static off and declare the variable as extern in the header:

extern Level* currentLevel;

This lets the compiler know that the storage for the variable is reserved elsewhere.


*See "Class Interface" in TOCPL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...