Typedef enum constant in .h file of class?

I'm programming an iPhone app and have my constants arranged in Constants.h and Constants.m file as recommended in this question: Constants in Objective-C.

My question is, if I define a typedef enum in Constants.h, and want to declare a property of that typedef enum in one of my classes .h files, what is the correct methodology for implementing that? Do I need to move the typedef enum out of Constants.h and in the classes .h file? Seems to defeat the purpose of having a global constants file...


A typedef creates a name that you can use as a type, like int , BOOL , or any other type: it's a type _def_inition. The compiler just needs to be able to see the typedef wherever you want to declare a variable of that type. That means all you need to do is import your Constants.h to the file where you want to use the type:

// Constants.h
typedef unsigned int Nimitz;

#import "Constants.h"

@interface Excelsior : NSObject

@property (assign) Nimitz numPlanes;

@end

My answer to these scope kinds of questions is to limit the declaration to the smallest scope needed.

If you only need the enum in your implementation, then put the declaration in the .m. If the enum is only needed with the interface, then put the declaration in the interface's .h. If the enum is needed by multiple independent interfaces, then I would resort to putting it in a global .h file.

I have two reasons for doing this. 1) Limiting scope reduces merging. 2) Limiting scope reduces the number of files effected by a change.

When all of your typedefs are in a single file, any time two developer updates any type, then one of them will have to merge on commit. I've dealt with enough errors created by bad merges in my life. I try to avoid them.

When you have a file that's included by every file in your program, then any change to that file will effect every file in your program. I've shipped production code that had bugs in modules that didn't have any commits. A change to a global include caused a problem that no one expected and no one tested for because it looked like the module was untouched.

链接地址: http://www.djcxy.com/p/57438.html

上一篇: 全局常量文件在Swift中

下一篇: 类中的.h文件中的typedef枚举常量