9

我有一个 DataClass.h

@interface DataClass : NSObject
{
}

enum knownTypes
{
    type1 = 0,
    type2,
    type3,
    UnknownType = -1
};

有没有办法可以在 .m 文件中指定 knownTypes 并从其他类访问。

这是我正在创建的 Util 类,因此不想创建一个对象来访问此类中的值。

例如:在 TestClass.m 中,通过导入 DataClass.h ,现在我可以将枚举值用作 type1,type2 .. 但如果我在 DataClass.m 中声明枚举数据,我将无法使用这些枚举值。

4

2 回答 2

18

This has nothing to do with classes. This is a feature of C.

If you define a type or an enum in a .h file, you can use it by importing it (#import) where you need it.

If you define your enum in a .c or .m file, only elements after that definition in the file can use it.

In your case, it appears that you need the same enum in two different files. Usage is to define that enum in a separate file, e.g., knownTypes.h and import that file in the two files using it: DataClass.m and TestClass.m.

If TestClass is for testing purpose, then your current organization is OK: enum is declared in DataClass.h and both DataClass.m and TestClass.m import DataClass.h.

于 2012-04-06T08:24:27.627 回答
2

不,如果您enum在源文件而不是标题中定义 ,那么只有该源文件才能使用enum. 如果您想保持它“私有”但可供多个源文件使用,请将其放在单独的标头中,并将此单独的标头包含在两个源文件中。

于 2012-04-06T07:22:46.327 回答